使用 IPC 在 while 循环中重定向标准输入

Using IPC to redirect stdin within a while loop

我正在尝试使用 C 在 linux 上将字符串写入剪贴板。我计划使用 xsel -ib(从标准输入中获取一个字符串并将其设置为当前剪贴板内容)。例如,在 bash 中,执​​行 echo Hello world | xsel -ib 会将 "Hello World" 设置到剪贴板中。

我的代码由一个简单的 IPC 组成,当我的程序(父程序)完成执行时它运行良好,但如果我将 IPC 包装在 while 循环中它就不起作用。

#include<unistd.h>
void main()
{
    while (1) { // 1
        int pipes[2] = { 0 };
        pipe(pipes);
        if (fork()) {
            close(pipes[0]);
            write(pipes[1], "hello world", sizeof("hello world"));
        } else {
            close(0);
            dup2(pipes[0], STDIN_FILENO);
            close(pipes[1]);
            execl("/usr/bin/xsel", "xsel", "-ib", NULL);
        }
        printf("\nTesting..");
        sleep(3); // 2
    } // 3
}

如果我删除由“1”、“2”和“3”注释的行,它就可以正常工作。但是有一个 while 循环对于我能够时不时地将不同的字符串输出到剪贴板是必不可少的。如何在不终止程序的情况下执行此操作。

这里有一些小改动,应该可以使程序更易于调试,并且至少可以解决一些问题。

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>
int main() /*correct declaration is int main()...*/
{
    while (1) { // 1
        int pipes[2] = { 0 };
        if (pipe(pipes)){
            perror("pipe() failed");
            exit(EXIT_FAILURE);
        }
        pid_t pid = fork();
        if (pid == -1){
            perror("fork() failed");
            exit(EXIT_FAILURE);
        }
        if (pid) {
            close(pipes[0]);
            write(pipes[1], "hello world", sizeof("hello world"));
            close(pipes[1]);
/*prevents file descriptor leak, also causes a read() to signal EOF rather than block indefinitely*/
            int status;
            wait(&status); /*prevents child zombification*/

        } else {
            close(0);
            dup2(pipes[0], STDIN_FILENO);
            close(pipes[1]);
            execl("/usr/bin/xsel", "xsel", "-ib", NULL);
        }
        printf("\nTesting..");
        sleep(3); // 2
    } // 3
}