child processes exit codes

J

just_james

Guest
Hello everyone,

I have to write in c a program which return an exit codes of three child processes. I know that wait() function can do that (writes to the ver so i wrote something like this:
Code:
#include <stdio.h>
#include <sys/wait.h>

int main(void)
{
int pid1,pid2,pid_from_wait,status,status2;
pid1=fork();
	if( pid1 != 0 ) 
	{
		pid_from_wait = wait(&status);
		printf("Child1 %d ended up with code %d \n",
pid_from_wait, status);
		pid2=fork();
			if( pid2 != 0 ); 
			{
				wait(&status2);
		printf("Child2 %d ended up with code %d \n", getpid(),
status2);
			}
			else 
			printf("I'm child 2");
			
	}
	else 
		printf("I'm child0");
return 0;
}

It doesn't work, could someone help me with that ?
 


man wait
Code:
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>

int main(void){
   pid_t chid, pid_from_wait;
   int status=0, cnt=0;

   chid=fork();
   if (chid== -1){ /* fork failed */
      perror("fork");
      exit(EXIT_FAILURE);
   }
   if (chid == 0) { /* child */
      printf("First child PID is %d\n", getpid());
      _exit(41);
   } 
   /* parent */
   chid=fork();
   if (chid == -1){ /* second fork failed */
      perror("second fork");
      exit(EXIT_FAILURE);
   }
   if (chid == 0) { /* second child */
      printf("Second child PID is %d\n", getpid());
      _exit(42);
   }
   /* parent */
   chid = fork();
   if (chid == -1){ /* third fork failed */
      perror("third fork");
      exit(EXIT_FAILURE);
   }
   if (chid == 0) { /* third child */
      printf("Third child PID is %d\n", getpid());
      _exit(43);
   }
   /* parent */
   do {
      pid_from_wait = wait(&status);
      if (pid_from_wait == -1) {
	 perror("wait");
	 exit(EXIT_FAILURE);
      }
      if (WIFEXITED(status)) {
	 cnt++;
	 printf("[%d] Child with pid %d ended up with code %d \n", cnt,
		pid_from_wait,  WEXITSTATUS(status));
      }
   } while (cnt < 3);
   exit(EXIT_SUCCESS);
}
http://c.pastebay.net/1161693
 

Members online


Top