c - testfork C 代码语法错误

标签 c syntax-error

我们应该使用类里面提供给我们的代码来学习 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/

相关文章:

c - 动态 C - 字符指针、strcpy、strcat

syntax-error - 如何在不退出 shell 的情况下在特定条件下停止采购 (t)csh 脚本?

function - Verilog 函数 - 无法找出我的错误

julia - [ Julia ]语法: invalid assignment location "getproperty(f, n)"

c - 使用 IMAP C-Client 获取正文部分 header

C 程序 sizeof 或宏,有问题

c - 我所有的 MPI 程序(用 c 语言编写)都会出现段错误

c - 为什么更多的线程需要更多的时间来处理?

php - PHP解析/语法错误;以及如何解决它们

python - Unicode解码错误: 'charmap' codec can't decode byte 0x81 in position 55: character maps to <undefined>