在我的eclipse中运行这个fork代码时出错,并且对这段代码也有一些概念混淆

时间:2015-06-10 17:13:01

标签: c logic output fork

所以这是我教授给我们的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;
}

1 个答案:

答案 0 :(得分:1)

改变这个:

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

到此:

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

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