- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
在下面的代码中,我只是试图通过标准输入将文件发送到将执行 cat OS 命令的子进程。代码编译得很好。这是我从命令行调用它的方式:
$ ./uniquify < words.txt
但是,当我运行它时,出现段错误。如果信息应该通过管道传递给 child ,我真的很难理解它是如何流动的。我试图使代码尽可能简单,以便我可以理解它,但它还没有意义。任何帮助将不胜感激。
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#define NUM_CHILDREN 2
int main(int argc, char *argv[])
{
pid_t catPid;
int writeFds[NUM_CHILDREN];
int catFds[2];
int c = 0;
FILE *writeToChildren[NUM_CHILDREN];
//create a pipe
(void) pipe(catFds);
if ((catPid = fork()) < 0) {
perror("cat fork failed");
exit(1);
}
//this is the child case
if (catPid == 0) {
//close the write end of the pipe
close(catFds[1]);
//close stdin?
close(0);
//duplicate the read side of the pipe
dup(catFds[0]);
//exec cat
execl("/bin/cat", "cat", (char *) 0);
perror("***** exec of cat failed");
exit(20);
}
else { //this is the parent case
//close the read end of the pipe
close(catFds[0]);
int p[2];
//create a pipe
pipe(p);
writeToChildren[c] = fdopen(p[1], "w");
} //only the the parent continues from here
//close file descriptor so the cat child can exit
close(catFds[1]);
char words[NUM_CHILDREN][50];
//read through the input file two words at a time
while (fscanf(stdin, "%s %s", words[0], words[1]) != EOF) {
//loop twice passing one of the words to each rev child
for (c = 0; c < NUM_CHILDREN; c++) {
fprintf(writeToChildren[c], "%s\n", words[c]);
}
}
//close all FILEs and fds by sending and EOF
for (c = 0; c < NUM_CHILDREN; c++) {
fclose(writeToChildren[c]);
close(writeFds[c]);
}
int status = 0;
//wait on all children
for (c = 0; c < (NUM_CHILDREN + 1); c++) {
wait(&status);
}
return 0;
}
最佳答案
由于您的问题似乎是关于了解管道和 fork 的工作原理,我希望下面的程序可以帮助您。请注意,这仅用于说明。它不符合商业实现的条件,但我想保持简短!
您可以按如下方式编译这两个程序:
cc pipechild.c -o pipechild
cc pipeparent.c -o pipeparent
然后用./pipeparent
执行
pipeparent.c源码
/* pipeparent.c */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define MESSAGE "HELLO!\n"
#define INBUFSIZE 80
#define RD 0 // Read end of pipe
#define WR 1 // Write end of pipe
int main(void)
{
int ptocpipe[2]; // Parent-to-child pipe
int ctoppipe[2]; // Chile-to-parent pipe
pid_t childpid; // Process ID of child
char inbuf[80]; // Input from child
int rd; // read() return
int rdup; // dup():ed stdin for child
int wdup; // dup():ed stdout for child
char *eol; // End of line
// Create pipe for writing to child
if (pipe(ptocpipe) < 0) {
fprintf(stderr, "pipe(ptocpipe) failed!\n");
return 2;
}
// Create pipe for writing back to parent
if (pipe(ctoppipe) < 0) {
fprintf(stderr, "pipe(ctoppipe) failed!\n");
return 2;
}
// Verify that one of the pipes are working by filling it first
// in one end and then reading it from the other. The OS will
// buffer the contents for us. Note, this is not at all necessary,
// it's just to illustrate how it works!
write(ptocpipe[WR], MESSAGE, strlen(MESSAGE));
read(ptocpipe[RD], inbuf, INBUFSIZE);
if (strlen(inbuf) != strlen(MESSAGE)) {
fprintf(stderr, "Failed to flush the toilet!\n");
return 6;
} else {
printf("Wrote to myself: %s", inbuf);
}
// Next, we want to launch some interactive program which
// replies with exactly one line to each line we send to it,
// until it gets tired and returns EOF to us.
// First, we must clone ourselves by using fork(). Then the
// child process must be replaced by the interactive program.
// Problem is: How do we cheat the program to read its stdin
// from us, and send its stdout back to us?
switch (childpid = fork()) {
case -1: // Error
fprintf(stderr, "Parent: fork() failed!\n");
return 3;
case 0: // Child process
// Close the ends we don't need. If not, we might
// write back to ourselves!
close(ptocpipe[WR]);
close(ctoppipe[RD]);
// Close stdin
close(0);
// Create a "new stdin", which WILL be 0 (zero)
if ((rdup = dup(ptocpipe[RD])) < 0) {
fprintf(stderr, "Failed dup(stdin)\n");
return 4;
}
// Close stdout
close(1);
// Create a "new stdout", which WILL be 1 (one)
if ((wdup = dup(ctoppipe[WR])) < 0) {
fprintf(stderr, "Failed dup(stdout)\n");
return 5;
}
// For debugging, verify stdin and stdout
fprintf(stderr, "rdup: %d, wdup %d\n", rdup, wdup);
// Overload current process by the interactive
// child process which we want to execute.
execlp("./pipechild", "pipechild", (char *) NULL);
// Getting here means we failed to launch the child
fprintf(stderr, "Parent: execl() failed!\n");
return 4;
}
// This code is executed by the parent only!
// Close the ends we don't need, to avoid writing back to ourself
close(ptocpipe[RD]);
close(ctoppipe[WR]);
// Write one line to the child and expect a reply, or EOF.
do {
write(ptocpipe[WR], MESSAGE, strlen(MESSAGE));
if ((rd = read(ctoppipe[RD], inbuf, INBUFSIZE)) > 0) {
// Chop off ending EOL
if ((eol = rindex(inbuf, '\n')) != NULL)
*eol = '\0';
printf("Parent: Read \"%s\" from child.\n", inbuf);
}
} while (rd > 0);
fprintf(stderr, "Parent: Child done!\n");
return 0;
}
pipechild.c源码
/* pipechild.c
* Note - This is only for illustration purpose!
* To be stable, we should catch/ignore signals,
* and use select() to read.
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <strings.h>
#include <string.h>
#define MAXCOUNT 5 // Maximum input lines toread
#define INBUFSIZE 80 // Buffer size
int main(void)
{
char buff[INBUFSIZE];
int remains = MAXCOUNT;
pid_t mypid;
char *eol;
mypid = getpid(); // Process-ID
fprintf(stderr, "Child %d: Started!\n", mypid);
// For each line read, write one tostdout.
while (fgets(buff, INBUFSIZE, stdin) && remains--) {
// Chop off ending EOL
if ((eol = rindex(buff, '\n')) != NULL)
*eol = '\0';
// Debug to console
fprintf(stderr, "Child %d: I got %s. %d remains.\n",
mypid, buff, 1 + remains);
// Reply to parent
sprintf(buff, "Child %d: %d remains\n", mypid, 1 + remains);
write(1, buff, strlen(buff));
}
fprintf(stderr, "Child %d: I'm done!\n", mypid);
return 0;
}
关于c - 如何将stdin通过管道传递给 child 并在C中执行猫,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16492666/
有使用过 Linux 系统的小伙伴,肯定会使用过 cat 这个命令。当然,在 Linux 下,此猫非彼猫,这里的 cat 并不代表猫,而是单词 concatenate 的缩写。 cat 命令是一个
Closed. This question needs to be more focused。它当前不接受答案。
我知道我可以穿越 List秒 import cats.instances.list._ import cats.syntax.traverse._ def doMagic(item: A): M[B]
标准库在List上提供了unzip方法: scala>val l = List((1, "one"), (2, "two"), (3, "three"), (4, "four"), (5, "five
我正在经历https://www.scala-exercises.org/对于猫来说。我想我明白Apply.ap 是什么意思。但我看不到它有任何用途。 有什么区别: Apply[Option].map
我是 cat 和函数式编程方面的新手,我正在努力对 EitherT 等函数式数据类型进行单元测试。有示例代码: class Library[F[_]]() { def create(book:
基本上我试图理解这些命令之间的区别: cat >(tee f.txt) echo yolo > >(tee t.txt) 前两个命令具有完全相同的结果:打印“yolo”,然后终端返回控制权,这正是我
我正在经历https://www.scala-exercises.org/对于猫来说。我想我明白Apply.ap 是什么意思。但我看不到它有任何用途。 有什么区别: Apply[Option].map
我是 cat 和函数式编程方面的新手,我正在努力对 EitherT 等函数式数据类型进行单元测试。有示例代码: class Library[F[_]]() { def create(book:
给定: import cats.syntax.cartesian._ type M[X] = Future[Either[Error, X]] val ma: M[A] = ??? val mb: M
我想使用来自该存储库的 cats-saga:https://github.com/VladKopanev/cats-saga 但是我卡在了 OrderSagaCoordinator.scala L16
假设我有: val x1: Either[String, Int] = Right(1) val x2: Either[String, Float] = Left("Nope") val x3: Ei
我正在重新编码 printf,我从 printf 获得的行为与真正的 printf 略有不同,因为我使用字符串(即 malloc),而真正的 printf 使用写入函数。 做的时候: ./a.out
这个问题在这里已经有了答案: What is PECS (Producer Extends Consumer Super)? (16 个答案) 关闭 5 年前。 这不是一个重复的问题,因为我特别询问
好的,所以我会更具体一些(自从我上一个问题以来)。 基本上,我有一个分页页面 - 有 3 个显示类别,但每个分页页面仅显示 50 个项目。因此,您可以获取占据一页的所有单个类别,或不同类别的组合 -
我在“Abb/test”文件夹中有一些 c 文件和 common.txt,在“Abb”文件夹中有 temp.txt。我想在所有 c 文件的标题中复制 common.txt 的内容。我正在使用以下 un
我有以下脚本 #!/bin/bash set i=0; while read line do echo "$line"; $i INFO 2013-08-16 13:46:48,660 In
我正在尝试为猫寻找一个例子 EitherT.collectRight 。我有一个EitherT[Future, String, Event]当我这样做时collectRight,我明白了 Error:
我有这段代码可以编译并且工作正常 import cats.implicits._ Cartesian[ValidResponse].product( getName(map).toValida
我有两个相同的文件,但它们的大小不同。这让我想到文件中有特殊字符,即 ^M 在第六章中 :set list 不显示 ^M 字符但是 cat -A 确实显示字符。 此外,VI 仅在出现在行尾时才显示特殊
我是一名优秀的程序员,十分优秀!