这是我的代码。当我尝试编译时,它给了我很多错误。我使用了gcc -o process process.c -lpthread。谁能帮我?我试过了“mamespace”,但这并没有帮助。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main()
{
int i, j;
int Num_of_children = 0;
pid_t pid[10];
pid_t return_pid;
return_pid = fork();
if(return_pid > 0) {
pid[Num_of_children] = return_pid;
Num_of_children = Num_of_children + 1;
}
return_pid = fork();
if(return_pid > 0) {
pid[Num_of_children] = return_pid;
Num_of_children = Num_of_children + 1;
}
else { Num_of_children = 0; }
if (Num_of_children > 0) {
return_pid = fork();
if(return_pid > 0) {
pid[Num_of_children] = return_pid;
Num_of_children = Num_of_children + 1;
}
else { Num_of_children = 0; }
}
for(j=0; j<3; j++) {
sleep(1+1000*rand()/RAND_MAX);
printf("PID: %d, Iteration: d%\n", getpid(), i);
}
for(j=0; j<Num_of_children; j++) waitpid(pid[j], NULL, 0);
}
答案 0 :(得分:1)
在启用警告的情况下构建您的程序,即gcc -Wall -g -lpthread process.c -o process
。然后,您将在代码中找到您所犯的错误:
process.c: In function ‘main’:
process.c:38:7: warning: unknown conversion type character 0xa in format [-Wformat=]
printf("PID: %d, Iteration: d%\n", getpid(), i);
^
process.c:38:7: warning: too many arguments for format [-Wformat-extra-args]
process.c:41:1: warning: control reaches end of non-void function [-Wreturn-type]
}
^
process.c:38:7: warning: ‘i’ may be used uninitialized in this function [-Wmaybe-uninitialized]
printf("PID: %d, Iteration: d%\n", getpid(), i);
^
所以修复错误并重建它。