[英]Is it possible to use pipe to create a comunication stream between 2 processes without using stderr, stdin or stdout?
就像問題一樣。 我可以連接 2 個通過 pipe() 發送信息但不使用 stdout、stdin 或 stderr 的進程(父進程和子進程)嗎? 我可以創建一個新的 stream 或緩沖區來使用嗎?
編輯:
我的子進程通過 execl() 啟動一個新程序,該程序需要通過管道與第一個程序通信,而不使用標准輸入和標准輸出。
我目前用於通過這些流進行通信的代碼如下:
#define READ 0
#define WRITE 1
pid_t
popen2(const char *command, int *infp, int *outfp)
{
int p_stdin[2], p_stdout[2];
pid_t pid;
if (pipe(p_stdin) != 0 || pipe(p_stdout) != 0)
return -1;
pid = fork();
if (pid < 0)
return pid;
else if (pid == 0)
{
close(p_stdin[WRITE]);
dup2(p_stdin[READ], READ);
close(p_stdout[READ]);
dup2(p_stdout[WRITE], 2);
execl("/bin/bash", "bash", "-c", command, NULL);
perror("execl");
exit(1);
}
if (infp == NULL)
close(p_stdin[WRITE]);
else
{
*infp = p_stdin[WRITE];
}
if (outfp == NULL)
close(p_stdout[READ]);
else
{
*outfp = p_stdout[READ];
}
return pid;
}
我目前正在我的子進程中從標准輸入讀取並寫入標准輸出。 如果我想從我創建的不同緩沖區讀取和寫入以防止由於打印和錯誤而可能導致的數據損壞怎么辦? 可能嗎?
井管用於您提到的確切目的。
這是 Beej 指南中的一個示例。
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
int main(void)
{
int pfds[2];
char buf[30];
pipe(pfds);
if (!fork()) {
printf(" CHILD: writing to the pipe\n");
write(pfds[1], "test", 5);
printf(" CHILD: exiting\n");
exit(0);
} else {
printf("PARENT: reading from pipe\n");
read(pfds[0], buf, 5);
printf("PARENT: read \"%s\"\n", buf);
wait(NULL);
}
return 0;
}
欲了解更多信息: https://beej.us/guide/bgipc/html/multi/pipes.html#pipesclean
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.