Hi, there. I've been trying to get my program to work for several hours now and I just can't fgure out what's wrong with my code. It's about passing a variable between processess using pipes. Each process increments it M times. The program works perfectly when I use shared memory, but when I change it to using pipes it's a disaster. Creating or using named pipes doesn't seem to work at all, or I guess I'm just doing it the wrong way. Here's the source code:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/mman.h>
#include <unistd.h>
#include <memory.h>
#include <fcntl.h>
#include <sys/stat.h>

#define PIPE_NAME	"MY_PIPE"
#define N 5
#define M 10

struct sembuf operations;	
int semid;			
key_t key;			
int marker;

void semWait(int semid, int sempos) {
	operations.sem_num = sempos; 		
	operations.sem_op = -1; 		
	operations.sem_flg = 0; 		

	if (semop(semid, &operations, 1) < 0) {
		perror("ERROR: semop wait\n");
		exit(-1);
	}
}


void semPost(int semid, int sempos) {
	operations.sem_num = sempos;		
	operations.sem_op = 1; 			
	operations.sem_flg = IPC_NOWAIT;	

	if (semop(semid, &operations, 1) < 0) {
		perror("ERROR: semop post\n");
		exit(-1);
	}
}


void worker(int id) {
	int j, nmarker;
	int fd = open(PIPE_NAME, O_RDWR);
	read(fd, &nmarker, sizeof(int));

	for (j = 0 ; j < M; j++) {
		semWait(semid, id);
		nmarker = nmarker + 1 ;
		printf("%d ", marker);
		semPost(semid, N); 				
	}
	
	write(fd, &nmarker, sizeof(nmarker));
	close(fd);
}

main() {
	int i, tempPID;
	int sarray[N+1] = {0};
	key = 23;
	marker = 0;

	
	if ((semid = semget(key , N+1, 0666 | IPC_CREAT)) == -1) {
		perror("ERROR: semget\n");
		exit(-1);	
	}

	
	if ((semctl(semid, N+1, SETALL, sarray)) < 0) {		
		perror("ERROR: semctl - val\n");
		exit(-1);
	}
	
	if(mkfifo(PIPE_NAME, S_IFIFO | 0666) < 0) {		
		perror("ERROR:pipe\n");
		exit(-1);
	}


	  int fd;
	  if( fd = open(PIPE_NAME, O_WRONLY) < 0 ){		
		perror("ERROR:open\n");
		exit(-1);
	} 
	
	write(fd, &marker, sizeof(marker));
	close(fd);
        

        for(i = 0; i < N; i++) {
                tempPID = fork();
		if (tempPID < 0) {
			perror("ERROR: fork\n");
			exit(-1);
		}
                else if (tempPID == 0) {	// if child
                        worker(i);
                        exit(0);
                }
        }
        
        
	for (i = 0 ; i < (M*N); i++) {
 		semPost(semid, i%N);		
		semWait(semid, N);			
	}

	printf("Marker = %d\n", marker);

	if (semctl( semid, 1, IPC_RMID ) == -1) {
		perror("ERROR: semctl free\n");
		exit(-1);
	}

     unlinc(PIPE_NAME);
}

I could really use some help, because I need to get this done by tomorrow. :S

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.