gpt4 book ai didi

c - 在我的 Eclipse 中运行此 fork 代码时出错,并且此代码也存在一些概念混淆

转载 作者:行者123 更新时间:2023-11-30 15:19:18 29 4
gpt4 key购买 nike

这是我的教授给我们的 Fork 上的一个简单的 C 代码,我试图获取该代码的输出,但是当我尝试在 Eclipse 中运行时,出现以下错误:

Info: Internal Builder is used for build
gcc -O0 -g3 -Wall -c -fmessage-length=0 -o ForkDemo1.o "..\\ForkDemo1.c"
..\ForkDemo1.c: In function 'main':
..\ForkDemo1.c:18:1: warning: implicit declaration of function 'fork' [-Wimplicit-function-declaration]
if( (pid = fork()) = -1) {
^
..\ForkDemo1.c:18:20: error: lvalue required as left operand of assignment
if( (pid = fork()) = -1) {

但是我对这段代码的基本困惑是:pid_t pid 的值是什么?是 11 还是 10,它是从父级创建子级吗?

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>


int global = 10;

int main(int argc, char* argv[]) {

int local = 0;
pid_t pid;


printf("Parent process: (Before fork())");
printf(" local = %d, global = %d \n", local, global);


if( (pid = fork()) = -1) {
perror("fork");
exit(1);
}
else if (0 == pid) {

/* child executes this branch */
printf("After the fork in the child:");
local++;
global++;
printf("local = %d, global = %d\n", local, global);
} else {
/* parent execute this branch */

sleep(2); /* sleep long enough for child's output to appear */
}

/* both process excute this print statement */
printf("pid = %d. local = %d, global = %d\n", getpid(), local, global);

return 0;
}

最佳答案

更改此:

if( (pid = fork()) = -1) {

对此:

if( (pid = fork()) == -1) {

关于fork隐式声明的警告,如果您在Windows操作系统中工作并使用gcc工具链进行MinGW,则可能会发生这种情况,它提供 unistd.h 但未实现 fork。在这种情况下,您应该切换到另一个环境。理想情况下 - Linux,但您也可以将 gcc 用于 Cygwin,它提供 fork

关于c - 在我的 Eclipse 中运行此 fork 代码时出错,并且此代码也存在一些概念混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30763003/

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