gpt4 book ai didi

c - fork() 代码

转载 作者:太空狗 更新时间:2023-10-29 17:16:17 26 4
gpt4 key购买 nike

void main ()
{
if ( fork () )
{
printf ( "PID1 %d\n", getpid () );
}
else
{
printf ( "PID2 %d\n", getpid () );
}
}

这段代码有什么作用?我知道它与进程 ID 有关,但不应该将某些东西返回到条件中以确定它是否是子/父进程?

最佳答案

一般是:

pid_t pid = fork();
if(pid == 0) {
//child
} else if(pid > 0) {
//parent
} else {
//error
}

手册页说:

RETURN VALUE   Upon successful completion, fork() shall return 0 to the child    process and shall return the process ID of the child process to the    parent process.  Both processes shall continue to execute from    the fork() function.    Otherwise, -1 shall be returned to the parent process, no child process    shall be created, and errno shall be set to indicate the error.

关于c - fork() 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2409086/

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