![](/img/trans.png)
[英]Pipes and fork() - How to write an array of int throught a pipe in C?
[英]How to write to the pipe fork?
我有以下功能,通過fork和execvp執行命令。 我在fork中啟動的腳本正在偵聽輸入數據。 如何將數據發送到myscript?
int external_command()
{
int pfds[2];
if (pipe(pfds) < 0)
return -1;
if ((uproc.pid = fork()) == -1)
return -1;
if (uproc.pid == 0) {
/* child */
const char *argv[4];
int i = 0;
argv[i++] = "/bin/sh";
argv[i++] = "myscript.sh";
argv[i++] = NULL;
close(pfds[0]);
dup2(pfds[1], 1);
close(pfds[1]);
execvp(argv[0], (char **) argv);
exit(ESRCH);
} else if (uproc.pid < 0)
return -1;
/* parent */
close(pfds[1]);
int status;
while (wait(&status) != uproc.pid) {
DD("waiting for child to exit");
}
char buffer[64];
ssize_t rxed;
char *c;
int t;
//read from fork pipe
*value = NULL;
while ((rxed = read(pfds[0], buffer, sizeof(buffer))) > 0) {
if (*value)
t = asprintf(&c, "%s%.*s", *value, (int) rxed, buffer);
else
t = asprintf(&c, "%.*s", (int) rxed, buffer);
if (t == -1) return -1;
free(*value);
*value = strdup(c);
free(c);
}
// how to write to the pipe fork?
}
管道是單向的。 調用兩次pipe
,以獲取一對文件描述符(用於從子級讀取數據)(如您所擁有的),以及另一對文件描述符,以將數據發送至子級(這將是新的)。 您需要像已經做的一樣執行相同的dup2
並close
魔術,以便將該新管道設置為孩子的stdin。
我猜你是說要從父進程寫入子進程stdin
? 為此,您需要創建兩個管道。 像您現在一樣,其中一個用作孩子的stdout
,另一個必須用作stdin
,與您現在使用的方式大致相同(但索引當然會顛倒)。
當然,您不能wait
孩子之后再寫它,因為如果孩子需要輸入才能繼續,則可能會陷入僵局。
管道基礎
請研究這段代碼,以便您了解自己在做什么
int fd[2]; /*write(fd[1],buffer,strlen)
/ read(fd[0],buffer2,SIZE)*/
pid_t cpid;
if(pipe(fd)==-1){
perror("pipe");
exit(EXIT_FAILURE);
}
if((cpid=fork())<0){/* FORK INIT */
printf("\n\tFORK ERROR\n");
exit(1);
}
if(cpid==0){ /*SON*/
close(fd[0]);
/********CODE******/
if((write(fd[1],final2,strlen(final2)))<0){
perror("\n\tWRITE ERROR");
}
close(fd[1]);
}else{ /*FATHER*/
close(fd[1]);
if((read(fd[0],aler,NN))<0){
perror("\n\tREAD ERROR");
}
wait(NULL);
/********CODE******/
close(fd[0]);
}
在這種情況下,父進程(父親)從new(son)進程中讀取()信息
如果您想進行BI方向的 read()write()創建2個管道(fd1 [2],fd2 [2])
使用與上述相同的邏輯,父親讀,關閉寫端fd1 [1],兒子寫,關閉讀端fd1 [0]
反之亦然
父親寫,關閉讀端fd2 [0],兒子讀,關閉寫端fd2 [1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.