process - Creating multiple processes in C -


i writing program needs create multiple processes. let's number 3. want each of these processes count , output 1 5, , sleep 1 second between each count/output. tried in following manner, sleep(1) did not work being interrupted. appreciate background on topic, did wrong, , how resolve this. here code far.

/*  * creates n > 2 processes.  */ int main(int argc, const char * argv[]) {     pid_t pid;      for(int = 0; < n_proc; i++) {         pid = fork();         if(pid == 0) {             processwork();             exit(0);         }     } }   /*  * work of single process.  */ void processwork() {     char buffer[buf_size];     (int = 1; <= 5; i++) {         sleep(1);         sprintf(buffer, "pid = %d, count = %d\n", getpid(), i);         write(1, buffer, strlen(buffer));     } } 

your sleep() works should work. however, problem seems parent process not wait termination of child processes, parent process terminates before children have performed work. thus, looks on unix system:

% ./a.out % pid = 41431, count = 1 pid = 41430, count = 1 pid = 41432, count = 1 pid = 41431, count = 2 pid = 41430, count = 2 pid = 41432, count = 2 pid = 41430, count = 3 pid = 41431, count = 3 pid = 41432, count = 3 pid = 41430, count = 4 pid = 41431, count = 4 pid = 41432, count = 4 pid = 41431, count = 5 pid = 41430, count = 5 pid = 41432, count = 5 

you should take @ manual page of wait() system call. can call system call in loop, , returns pid of terminated child long there children, , -1 errno == echild once you've run out of children. echild can used loop termination criterion.


Comments

Popular posts from this blog

java - Could not locate OpenAL library -

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

sorting - opencl Bitonic sort with 64 bits keys -