gpt4 book ai didi

c - fork() 返回一个大于 0 的数字

转载 作者:行者123 更新时间:2023-11-30 20:31:26 24 4
gpt4 key购买 nike

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <sys/types.h>
// Curtis
void kloop(int x)
{
int breakCondition;
breakCondition = 0;
while(1)
{
printf("Process %d running\n", x);
sleep(1);

breakCondition = breakCondition + 1;
if (breakCondition == 5)
{
break;
}
}
}

//----------------

void makeChild()
{
int status;
pid_t pid;
pid = fork();

printf("fork number %d\n", pid);
printf("processid: %d", getpid());

if (pid < 0)
{
printf("You done messed up.\n");
}
else if (pid == 0)
{
printf("You are in child process %d\n", getpid());
}
else
{
printf("You ain't no kid.\n");
}

printf("fork number after if/else: %d\n", pid);
printf("processid after if/else: %d\n", getpid());
}

//----------------

int main()
{
int status;
int n;
printf("How many child processes do you want to create?\n");
scanf("%d", &n);

printf("\n");

kloop(n);

int i;
for (i=0;i<n;i++)
{
//printf("\t'i' at %d", i);
makeChild();
}
return 0;
}

这是一个 .c 文件,我使用 gcc 和 ./a.out 在终端中运行它。当我以前使用 fork 时,它通常给我一个等于 0 或更小的值。在本例中,它看起来像一个 processid。

以下是输出示例:

您要创建多少个子进程?

1

进程1正在运行

进程1正在运行

进程1正在运行

进程1正在运行

进程1正在运行

叉号10572

processid:10566你不是 child 子。

if/else 之后的 fork 号:10572

if/else 之后的 processid:10566

叉号0

processid: 10572您位于子进程 10572

if/else 后的 fork 号:0

if/else 之后的 processid:10572

最佳答案

使用fork的基本模式是这样的。

void makeChild() {
pid_t pid = fork();

// Error
if (pid < 0) {
fprintf(stderr, "fork() failed: %s\n", strerror(errno));
}
// Child
else if (pid == 0) {
printf("Child, pid %d, ppid %d\n", getpid(), getppid());

doSomething();

// This is the important piece, the child branch must exit.
exit(0);
}
// Parent
else {
printf("Parent, pid %d. Child pid is %d\n", getpid(), pid);
}
}

在父级和子级的fork之后继续处理。唯一的区别是 parent 和 child 收到的内容不同。子进程接收 0,父进程接收子进程的 pid。

$ ./test
Parent, pid 35324. Child pid is 35325
Child, pid 35325, ppid 35324

关键的是,一旦子分支完成了正在做的事情,子分支必须退出,否则它将继续运行其余的代码。

关于c - fork() 返回一个大于 0 的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51032840/

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