31.8k views
5 votes
Write a program that prints "Hello, World!" from a child process it creates and prints the ids of the child and parent processes in the format "The child and parent process ids are: 1234 and 1235." A failure of fork() should be caught and printed as an error message using err_sys call.

User Daparic
by
7.3k points

1 Answer

4 votes

Answer:

#include <stdio.h>

#include <stdlib.h>

#include <sys/wait.h>

#include <unistd.h>

#include <sys/types.h> //NOTE: Added

void err_sys(const char *x)

{

printf("\\");

perror(x);

printf("\\");

exit(1);

}

void main()

{

pid_t pid;

if( (pid = fork()) == -1 )

{

err_sys("fork failed");

}

else if( pid == 0 )

{

printf("\\Hello, World!\\");

printf("The child and parent ids are: %d and %d.\\\\", getpid(), getppid());

}

else

{

wait(NULL);

}

}

User Salsa
by
7.0k points