C : initializer element is not constant

标签 c io fork element

我正在用 C 学习 fork(),但我遇到了这些错误:

app.c:13:1: warning: data definition has no type or storage class [enabled by default]
app.c:13:1: error: initializer element is not constant
app.c:15:1: error: expected identifier or ‘(’ before ‘if’
app.c:20:1: error: expected identifier or ‘(’ before ‘else’
app.c:26:1: error: expected identifier or ‘(’ before ‘else’

这是源代码:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>

int f;
pid_t pid;

char msga[] = "abcd";
char msgb[] = "wxyz";

f = open("toto", O_WRONLY|O_TRUNC|O_CREAT,S_IRUSR|S_IWUSR);

if ((pid = fork()) == -1) {
    perror("fork");
    exit(EXIT_FAILURE);
}

else if (pid == 0) {
    wait(NULL);
    write(f, &msga, strlen(msga));
    close(f);
}

else {
    wait(NULL);
    write(f, &msgb, strlen(msgb));
    close(f);
}

最佳答案

您需要将所有这些(在 #include 行之后)包装在一个函数中!

int main(void)
{
 ...
}

您可能还想在末尾添加一个 return 0;

在这里进行快速测试,我还需要添加:

#include <unistd.h>
#include <string.h>

分别获取fork(2)strlen(3)的声明。

关于C : initializer element is not constant,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16887641/

相关文章:

c - 程序正在跳过 fgets 且不允许输入

c# - 将列表写入csv文件c#

c - C 中的动态分配和释放

c - 如何使用结构体成员初始化结构体?

在C中将字符串的一部分复制到另一部分

c# - 如果路径不存在,如何检查字符串路径是 'File' 还是 'Directory'?

c - PF_BRIDGE(NF_BR_PRE_ROUTING) Hook 未被调用

c - parent 从文件中读取操作, child 将其与 bc 相加

c - 使用多个进程读取文件并通过pipe()发送数字

c - C 中的 signal() 不起作用