gpt4 book ai didi

c - fork 指令

转载 作者:行者123 更新时间:2023-11-30 20:06:14 28 4
gpt4 key购买 nike

我的问题是关于 C 中的 fork() 指令。我有以下程序:

void main(){
int result, status;
result = fork();
if(result==0){
printf("Son:%d\n", getpid());
}else{
printf("Pai..:%d\n", getpid());
wait(&status);
}
}

为什么我收到两个 printf,而不是一个?是因为 fork 的回归吗?我的另一个问题是关于 & before 状态。为什么我需要它?

最佳答案

fork 是一种进程创建自身副本的操作。它通常是一个系统调用,在内核中实现。 Fork是类Unix操作系统上创建进程的主要方法。在多任务操作系统中,进程(正在运行的程序)需要一种创建新进程的方法

当一个进程调用fork时,它被视为父进程,新创建的进程被视为其子进程。 fork 后,两个进程不仅运行相同的程序,而且它们恢复执行,就像都调用了系统调用一样。然后,他们可以检查调用的返回值以确定其状态(子级还是父级),并采取相应的操作。

    /* Includes */
#include <unistd.h> /* Symbolic Constants */
#include <sys/types.h> /* Primitive System Data Types */
#include <errno.h> /* Errors */
#include <stdio.h> /* Input/Output */
#include <sys/wait.h> /* Wait for Process Termination */
#include <stdlib.h> /* General Utilities */

int main()
{
pid_t childpid; /* variable to store the child's pid */
int retval; /* child process: user-provided return code */
int status; /* parent process: child's exit status */

/* only 1 int variable is needed because each process would have its
own instance of the variable
here, 2 int variables are used for clarity */

/* now create new process */
childpid = fork();

if (childpid >= 0) /* fork succeeded */
{
if (childpid == 0) /* fork() returns 0 to the child process */
{
printf("CHILD: I am the child process!\n");
printf("CHILD: Here's my PID: %d\n", getpid());
printf("CHILD: My parent's PID is: %d\n", getppid());
printf("CHILD: The value of my copy of childpid is: %d\n", childpid);
printf("CHILD: Sleeping for 1 second...\n");
sleep(1); /* sleep for 1 second */
printf("CHILD: Enter an exit value (0 to 255): ");
scanf(" %d", &retval);
printf("CHILD: Goodbye!\n");
exit(retval); /* child exits with user-provided return code */
}
else /* fork() returns new pid to the parent process */
{
printf("PARENT: I am the parent process!\n");
printf("PARENT: Here's my PID: %d\n", getpid());
printf("PARENT: The value of my copy of childpid is %d\n", childpid);
printf("PARENT: I will now wait for my child to exit.\n");
wait(&status); /* wait for child to exit, and store its status */
printf("PARENT: Child's exit code is: %d\n", WEXITSTATUS(status));
printf("PARENT: Goodbye!\n");
exit(0); /* parent exits */
}
}
else /* fork returns -1 on failure */
{
perror("fork"); /* display error message */
exit(0);
}
}

关于c - fork 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26284045/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com