Last active
December 4, 2022 21:12
-
-
Save nikanos/45e997d05ec86b9ac12039cd8de45e4b to your computer and use it in GitHub Desktop.
linux fork() C example - parent process starts a child process that sleeps for 3 seconds and either waits or terminates it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <time.h> | |
#include <sys/wait.h> | |
#include <unistd.h> | |
int main() | |
{ | |
int pid; | |
int status; | |
if ((pid = fork()) > 0) | |
{ | |
puts("Parent waiting..."); | |
srand(time(NULL)); | |
if (rand() % 2) | |
{ | |
puts("sending signal SIGKILL"); | |
kill(pid, SIGKILL); | |
} | |
wait4(pid, &status, 0, NULL); | |
puts("Parent stopped waiting"); | |
if (WIFEXITED(status)) | |
puts("Child exited successfully"); | |
if (WIFSIGNALED(status)) | |
puts("Child terminated by a signal"); | |
} | |
else | |
{ | |
if (pid == 0) | |
{ | |
/*Child*/ | |
char *argv[] = { "/bin/sleep", "3", NULL}; | |
execve("/bin/sleep", argv, NULL); | |
} | |
else | |
{ | |
fprintf(stderr, "fork() failure\n"); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment