有关如何避免在 write() 上出现错误文件描述符错误的任何建议?

问题描述 投票:0回答:1

我已经这样做有一段时间了,我不确定为什么我不断收到错误的文件描述符错误,我想这可能与clone()函数以及我如何尝试将管道作为争论,但我不确定,我试过在网上查找,但仍然没有找到答案。我确实尝试过使用信号仍然无法使其工作。

#define _GNU_SOURCE
#include <stdlib.h>
#include <malloc.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <sched.h>
#include <stdio.h>
#include <unistd.h>

// 64kB stack
#define FIBER_STACK (1024*64)

int threadFunction(void* argument)
{
    int pipefd = *((int*)argument);
  
    char* info = "INFO!\n";
    if (write(pipefd, info, 10) == -1) {
      perror("write");
      exit(EXIT_FAILURE);
    }
    
    printf("Child thread exiting\n");
    return 0;
}

int main()
{
    void* stack;
    pid_t pid;
    int pipefd[2];

    if (pipe(pipefd) == -1)
    {
        perror("pipe");
        exit(EXIT_FAILURE);
    }

    // Allocate the stack
    stack = malloc(FIBER_STACK);
    if (stack == 0)
    {
        perror("malloc: could not allocate stack");
        exit(EXIT_FAILURE);
    }


printf("Creating child thread\n");

    // Call the clone system call to create the child thread
    pid = clone(&threadFunction, (char*)stack + FIBER_STACK,
                SIGCHLD | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_VM,(void*)&pipefd[1]); 
    if (pid == -1)
    {
        perror("clone");
        exit(EXIT_FAILURE);
    }

    close(pipefd[1]);

    char buffer[1024];
  
    
    /* read pipe */
    read(pipefd[0], buffer, 5); 
    printf("%s \n", buffer); 
     

    pid = waitpid(pid, 0, 0);
    if (pid == -1)
    {
        perror("waitpid");
        exit(EXIT_FAILURE);
    }

    free(stack);
    printf("Child thread returned and stack freed.\n");

    return 0;
}

理论上,代码应该能够运行 write() 函数,但我只是不断收到错误的文件描述符错误,我真的不知道我在这里错过了什么,这对我完全没有帮助管道概念的新手。

c pipe
1个回答
0
投票

CLONE_FILES(自 Linux 2.0 起)

如果设置了 CLONE_FILES,则调用进程和子进程 进程共享相同的文件描述符表。

但你确实:

关闭(pipefd[1]);

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.