使用 putty 运行 fork() 函数程序时出错

使用 putty 运行 fork() 函数程序时出错
#include<stdio.h>
#include<sys/wait.h>

int main()
{
int p1,p2;
p1=fork();
if(p1==-1)
{
printf(“Error”);
}
else
{
printf(“Parent is %d, Child is %d n”,getppid(),getpid());
}
p2=fork();
printf(“Parent is %d, Child is %d n”,getppid(),getpid());

return 0;

abcd.c: In function ‘main’:
abcd.c:7:4: warning: implicit declaration of function ‘fork’ [-Wimplicit-function-declaration]
 p1=fork();
    ^
abcd.c:10:1: error: stray ‘\342’ in program
 printf(“Error”);
 ^
abcd.c:10:1: error: stray ‘\200’ in program
abcd.c:10:1: error: stray ‘\234’ in program
abcd.c:10:1: error: stray ‘\342’ in program
abcd.c:10:1: error: stray ‘\200’ in program
abcd.c:10:1: error: stray ‘\235’ in program
abcd.c:10:11: error: ‘Error’ undeclared (first use in this function)
 printf(“Error”);
           ^
abcd.c:10:11: note: each undeclared identifier is reported only once for each function it appears in
abcd.c:14:1: error: stray ‘\342’ in program
 printf(“Parent is %d, Child is %d n”,getppid(),getpid());
 ^
abcd.c:14:1: error: stray ‘\200’ in program
abcd.c:14:1: error: stray ‘\234’ in program
abcd.c:14:11: error: ‘Parent’ undeclared (first use in this function)
 printf(“Parent is %d, Child is %d n”,getppid(),getpid());
           ^
abcd.c:14:18: error: expected ‘)’ before ‘is’
 printf(“Parent is %d, Child is %d n”,getppid(),getpid());
                  ^
abcd.c:14:18: error: stray ‘\342’ in program
abcd.c:14:18: error: stray ‘\200’ in program
abcd.c:14:18: error: stray ‘\235’ in program
abcd.c:17:1: error: stray ‘\342’ in program
 printf(“Parent is %d, Child is %d n”,getppid(),getpid());
 ^
abcd.c:17:1: error: stray ‘\200’ in program
abcd.c:17:1: error: stray ‘\234’ in program
abcd.c:17:18: error: expected ‘)’ before ‘is’
 printf(“Parent is %d, Child is %d n”,getppid(),getpid());
                  ^
abcd.c:17:18: error: stray ‘\342’ in program
abcd.c:17:18: error: stray ‘\200’ in program
abcd.c:17:18: error: stray ‘\235’ in program

答案1

您需要添加

#include <unistd.h>

要使用fork,请将所有内容更改为并在末尾"添加结尾:}

#include<stdio.h>
#include<sys/wait.h>
#include <unistd.h>

int main()
{
int p1,p2;
p1=fork();
if(p1==-1)
{
printf("Error");
}
else
{
printf("Parent is %d, Child is %d n",getppid(),getpid());
}
p2=fork();
printf("Parent is %d, Child is %d n",getppid(),getpid());

return 0;
}

相关内容