c - fork() 使用不当?

标签 c linux fork

我正在尝试使用 fork() 来实现消息队列。这就是我得到的。

#define DATA_SIZE 256
#define BUFF_SIZE 4096

int main(void) {
    // seed the random number generator
    srand(time(NULL));

    // Parent and Ground Truth Buffers
    char ground_truth[BUFF_SIZE]    = {0};  // used to verify
    char producer_buffer[BUFF_SIZE] = {0};  // used by the parent
    int i = 0;  
    int msqid = 0;
    int rc;
    pid_t msq_pid;

    for (i = 0; i < BUFF_SIZE; ++i) {
        producer_buffer[i] = ground_truth[i] = rand() % 256;
    }

    const key_t s_msq_key = 1337;  // used to create message queue ipc
    const char *const p_msq_key = "/OS_MSG";

    msqid = msgget(s_msq_key, IPC_CREAT | 0660);

    msq_pid = fork();

    if(msq_pid == -1){
       perror("error forking");
       exit(1);
    }

    if(msq_pid > 0){
        rc = msgsnd(msqid, (void*)p_msq_key, sizeof(producer_buffer), 0);
        printf("MESSAGE SENT\n");
        if(rc < 0){
            perror("message send failed");
            exit(1);
        }
        return 1;
    } else {
        if(memcmp(producer_buffer, ground_truth, DATA_SIZE) == 0){
            printf("MESSAGE REC");
            return 1;
        }
        exit(1);
    }

return 0;
}

我添加了我的实际问题。希望这不是太多。这是一项家庭作业,但我不想只获得代码方面的帮助。再一次,我得到的唯一结果是 MESSAGE REC 而不是 MESSAGE SENT 后跟 MESSAGE REC

编辑:

好的,我为 msq_pid == -1 添加了错误检查。我还注意到,当我重新启动我的虚拟机时,我能够获得 MESSAGE SENTMESSAGE REC。程序再运行几次后,我开始只收到 MESSAGE REC。谁能解释一下?

最佳答案

根据 fork()手册页看来你的问题是你的 child 和 parent 倒置了。 fork() 向子进程返回 0,向父进程返回 > 0,出错时返回 -1。所以在你的代码中你应该有:

if(msg_pqid == 0) { 
     /* The child sends the message */ 
} else { 
    /* Parent receives the message */ 
}

我更喜欢这样使用开关:

switch ((msg_pqid = fork())) {
case -1: 
    /* Error */
case 0:
    /* Child sends message */
default:
    /* Parent receives message */
}

关于c - fork() 使用不当?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37016850/

相关文章:

linux - ksh shell 脚本查找字符串中第一次出现的 _ 并删除所有内容,直到出现

c++ - Windows 最接近 fork() 的是什么?

linux - 在Linux CLI中按位置替换特定行上的特定字符

c - 通过 C 中的管道读取/写入

c - SIGPIPE中一个简单的二进程程序

c++ - ODBC 调用 SQLFetch 与 SQLFetchScroll

c - 如何使用 strtok() token

c - 动态二维数组好像要分配更多的内存

c - Qsort 和 Comparators 奇怪的行为。 C

python - 如何检查ppp连接是否繁忙