Total C noob,寻求fork()
的帮助。我不确定为什么它打印子进程2代码两次。我认为它与sleep
调用有关,因为它之前工作正常。
Child Process 2
Process ID: 31973
Parent Process ID: 1
Child Process 1
Process ID: 31972
Parent Process ID: 1
Child Process 2
Process ID: 31974
Parent Process ID: 1
#define _XOPEN_SOURCE // required for cuserid to work
// includes
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/resource.h>
#include <time.h>
int main(void) {
getP0Info();
putenv("WHALE=7");
forkProcesses();
return 0;
}
// Prints an error message and exits if one occurs. Else, returns the system call value.
int print_if_err(int syscall_val, const char* syscall_name) {
if (syscall_val < 0) {
perror(syscall_name);
exit(errno);
} else {
//No syscall error; we can return
return syscall_val;
}
}
void forkProcesses() {
pid_t child1_pid = print_if_err(fork(), "fork");
if (child1_pid == 0) {
printf("\nChild Process 1\n");
printf("Process ID: %d\n", getpid());
printf("Parent Process ID: %d\n", getppid());
sleep(1);
int whale = atoi(getenv("WHALE"));
printf("C1: %d\n", whale);
}
pid_t child2_pid = print_if_err(fork(), "fork");
if (child2_pid == 0) {
printf("\nChild Process 2\n");
printf("Process ID: %d\n", getpid());
printf("Parent Process ID: %d\n", getppid());
}
}
答案 0 :(得分:2)
这是因为即使在if语句结束后,子进程1的执行仍在继续。您需要明确地执行return
或致电_exit()
等,以防止这种情况发生:
void forkProcesses() {
pid_t child1_pid = print_if_err(fork(), "fork");
if (child1_pid == 0) {
printf("\nChild Process 1\n");
printf("Process ID: %d\n", getpid());
printf("Parent Process ID: %d\n", getppid());
sleep(1);
int whale = atoi(getenv("WHALE"));
printf("C1: %d\n", whale);
_exit(0);
}
pid_t child2_pid = print_if_err(fork(), "fork");
if (child2_pid == 0) {
printf("\nChild Process 2\n");
printf("Process ID: %d\n", getpid());
printf("Parent Process ID: %d\n", getppid());
}
}