c - C 脚本中的意外标记 "("

标签 c unix process fork

我正在尝试编写一个创建子进程的 C 脚本,并根据返回值打印一条消息。到目前为止我写了这段代码:

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>

int main ()
{
 pid_t child_pid;
 printf ("the main program process ID is %d\n", (int) getpid()); 
 child_pid = fork() ; 
 if (child_pid==0){
    printf("this is the child process,with the id %d\n",(int) child_pid );
}
 else
    printf("this is the parent process with id %d\n",(int) getpid ());

 return 0;
}

当我尝试编译它时,它似乎没问题。但是当我在终端中运行它时,出现以下错误:

./lab7.c: line 6: syntax error near unexpected token `('
./lab7.c: line 6: `int main ()'"

有人可以告诉我我做错了什么吗?

最佳答案

听起来您正在将源代码作为脚本而不是可执行文件来执行,而且,毫不奇怪,无论您在哪个 shell 中都不喜欢它。

您需要先编译代码,然后执行编译结果。例如,这里我们在第一行编译生成名为 lab7 的可执行文件,并在第二行执行它:

gcc -Wall -Wextra lab7.c -o lab7
./lab7

关于c - C 脚本中的意外标记 "(",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29447904/

相关文章:

bash - 为什么带有 -w (--word-regexp) 标志的 grep 如此缓慢且占用大量内存?

unix - 在 '=' 之后使用 sed 返回值

c - 退出程序会不会自动关闭管道?

c - 如何计算我的 frameCount 函数中的堆栈帧数?

c - 为什么我的循环会创建额外的链表节点?

c - parent 如何等待所有子进程完成然后在收到 SIGINT 时退出?

powershell - 使用 Powershell 操作 Windows 进程输入/输出流?

c - 设置正确的文件路径

c - C 中的变量重用

macos - OS X 是否支持 POSIX session ?