编写一个linux的管道程序

编写一个linux的管道程序,第1张

对此程序有问题,可以baidu hi我。

#include <stdio.h>

#include <unistd.h>

#include <stdlib.h>

int main()

{

int pid1, pid2

int pfd[2]

pipe(pfd)

pid1 = fork()

if (pid1 == 0)

{

char * argv[] = {

"echo",

"good morning",

NULL

}

/* left child */

close(pfd[0])

close(1)/* close stdout */

dup(pfd[1])/* redirect stdout to pipe */

close(pfd[1])

execvp("echo", argv)

exit(1)

}

pid2 = fork()

if (pid2 == 0)

{

char *argv[] = {

"sed",

"s/good/hi/g",

NULL

}

/* right child */

close(pfd[1])

close(0)/* close stdin */

dup(pfd[0])/* redirect stdin to pipe */

close(pfd[0])

execvp("sed", argv)

exit(1)

}

close(pfd[0])

close(pfd[1])

wait(NULL)

wait(NULL)

printf("Both children exited.\n")

return 0

}

//具体不懂得地方你晚上再问我吧

#include<unistd.h>

#include<stdio.h>

#include<sys/types.h>

#include<stdlib.h>

#include<fcntl.h>

#include<string.h>

int main(int argc, char *argv) {

int fd[2]

int len

pid_t pid

char filename[10]

char childbuf[10]

if (pipe(fd) <0) {

perror("pipe error!")

exit(1)

}

if ((pid = fork()) <0) {

perror("fork error!")

exit(1)

}

if (pid == 0) {

close(fd[1])

len = read(fd[0], childbuf, 100)

childbuf[len] = '\0'

printf("%s\n", childbuf)

if (execlp("cat", "cat", childbuf, (char*) 0) <0) {

perror("exec error!")

exit(1)

}

} else {

close(fd[0])

printf("请输入文件名\n")

scanf("%s", filename)

write(fd[1], filename, strlen(filename))

waitpid(pid, NULL, 0)

return 0

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/yw/7180666.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-02
下一篇2023-04-02

发表评论

登录后才能评论

评论列表(0条)

    保存