54 lines
1.1 KiB
C
54 lines
1.1 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <sys/types.h>
|
|
#include <unistd.h>
|
|
|
|
static int example_of_forks() {
|
|
pid_t pid;
|
|
|
|
pid = fork();
|
|
if (pid == 0) {
|
|
// child process
|
|
printf("This is Child, pid: %d\n", pid);
|
|
} else if (pid > 0) {
|
|
// parent process
|
|
printf("This is father, pid: %d\n", pid);
|
|
} else {
|
|
printf("fork err!\n");
|
|
return -1;
|
|
}
|
|
|
|
pid = fork();
|
|
if (pid == 0) {
|
|
printf("This is Child, pid: %d\n", pid);
|
|
} else if (pid > 0) {
|
|
printf("This is father, pid: %d\n", pid);
|
|
} else {
|
|
printf("fork err!\n");
|
|
return -1;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
int InChild = 0;
|
|
|
|
void initChildProcess() {
|
|
InChild = 1;
|
|
}
|
|
|
|
int main(int argc, char** argv) {
|
|
pid_t pid;
|
|
pid = fork();
|
|
if (pid < 0) {
|
|
printf("Fork fails\n");
|
|
return -1;
|
|
} else if (pid > 0) {
|
|
printf("Pid: %d, InChild: %d\n", getpid(), InChild);
|
|
} else {
|
|
initChildProcess();
|
|
printf("Pid: %d, InChild: %d\n", getpid(), InChild);
|
|
}
|
|
|
|
return 0;
|
|
}
|