语法错误testfork C代码

Syntax Error testfork C code

我们应该使用 class 中提供给我们的这段代码来了解分叉的工作原理以及我们看到的不同输入的差异。我唯一的问题是当我尝试 运行 代码时收到语法错误,所以我不确定我做错了什么。非常感谢任何帮助或指导。

编辑:忘了说明我是如何运行宁此的。学校有一台我连接到 运行 的 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;
}

代码似乎是正确的(我在这里只谈论语法),我可以编译并且运行它在我的电脑上完全没问题。所以问题可能出在你 compile/run 文件的方式上。这是一个 .c 文件,因此您可能需要使用 gcc 编译器,例如:

gcc your_file.c -o your_exe -Wall -Wextra-Wall -Wextra 是可选的,但这始终是一个好习惯)。

然后你会发现一个名为 your_exe 的新文件,你可以像这样执行 ./your_exe(假设你在 Linux 机器上)。

希望对您有所帮助!

刚试过这个

sh-4.3$ gcc -o testforkx testfork.c                                                                                                                                                                           
sh-4.3$ ls                                                                                                                                                                                                    
testfork.c  testforkx                                                                                                                                                                                         
sh-4.3$ ./testforkx 12

这是我得到的输出:

parent process
parent process
parent process
parent process
parent process
parent process
parent process
parent process
parent process
parent process
parent process
parent process
                   CHILD PROCESS
                   CHILD PROCESS
                   CHILD PROCESS
                   CHILD PROCESS
                   CHILD PROCESS
                   CHILD PROCESS
                   CHILD PROCESS
                   CHILD PROCESS
                   CHILD PROCESS
                   CHILD PROCESS
                   CHILD PROCESS
                   CHILD PROCESS

在程序中没有发现任何语法错误