-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfork_exec.c
More file actions
58 lines (35 loc) · 1.31 KB
/
fork_exec.c
File metadata and controls
58 lines (35 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
void signal_handler(int status){
printf("\nParent exiting with ");
if(WIFEXITED(status))
printf("Child return code %d\n",WEXITSTATUS(status));
else if(WIFSIGNALED(status))
printf("Child terminated abnormally by signal number %d\n",WTERMSIG(status));
else
printf("not known\n");
exit(1);
}
int main(int argc, char *argv[]){
pid_t pid;
int rv; // exit return value o child
char * arg[] = {"ls", "-l", NULL};
signal(SIGINT,signal_handler); // define the signal handler function in case of signalled interrupts
printf("Parent pid %d\n",getpid());
printf("Parent executing\n");
pid = fork(); // fork process
if(pid == 0){
printf("Child executing\n");
execvp(arg[0], arg); // execute ls command with -ls flag
}
wait(&rv);
printf("\nParent exiting with ");
if(WIFEXITED(rv)) // check if exited normally
printf("Child return code %d\n",WEXITSTATUS(rv)); // print exit status
exit(0);
}