我们应该使用类里面提供给我们的代码来学习 fork 的工作原理以及我们在不同输入下看到的差异。我唯一的问题是,当我尝试运行代码时收到语法错误,所以我不确定我做错了什么。非常感谢任何帮助或指导。
编辑:忘记澄清我是如何运行这个的。学校有一台 UNIX 机器,我连接到它来运行它。编译后只需使用其文件名 testfork.c 运行它
错误输出:
./testfork.c: line 6: syntax error near unexpected token `('
./testfork.c: line 6: `int main(int argc, char *argv[])'
代码块:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
pid_t childpid; int count;
if (argc < 2) {
printf("usage: testfork count\n");
return -1;
}
else count = atoi(argv[1]);
childpid = fork();
if (childpid == -1) {
printf("Error in fork; program terminated\n");
return -1;
}
if (childpid != 0) {
/*Code executed by parent process*/
int i;
/*The lines below will avoid output interleaving*/
/*int status;*/
/*wait(&status);*/
for (i = 0; i < count; i++)
printf("parent process\n");
}
else {
/*Code executed by child process*/
int j;
for (j = 0; j < count; j++)
printf(" CHILD PROCESS\n");
}
return 0;
}
最佳答案
代码似乎是正确的(我在这里只讨论语法),并且我可以在我的计算机上完美地编译和运行它。所以问题可能来自于你编译/运行文件的方式。这是一个 .c 文件,因此您可能需要使用 gcc
编译器,例如:
gcc your_file.c -o your_exe -Wall -Wextra
(-Wall -Wextra
是可选的,但这始终是一个好习惯)。
然后您将找到一个名为 your_exe
的新文件,您可以像 ./your_exe
一样执行该文件(假设您使用的是 Linux 计算机)。
希望这有帮助!
关于c - testfork C 代码语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35383890/