我正在尝试将代码从 C# 重写为 C,但遇到了一些麻烦。
所以我有一个名为 test 的文件,其中有一行文本。我想读取该行,通过进程之间的管道发送并将其打印在屏幕上。
代码如下:
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
void
read_from_pipe (int file)
{
FILE *stream;
int c;
stream = fdopen (file, "r");
while ((c = fgetc (stream)) != EOF)
putchar (c);
fclose (stream);
}
void
write_to_pipe (int file)
{
FILE *stream;
FILE *testfile;
stream = fdopen (file, "w");
testfile = fopen("test.txt", "r");
char *line = NULL;
size_t len = 0;
//ssize_t read;
getline(&line, &len, testfile);
fprintf (stream, "%s", line);
free(line);
fclose(testfile);
fclose (stream);
}
int
main (void)
{
pid_t pid;
int mypipe[2];
if (pipe (mypipe))
{
fprintf (stderr, "Pipe failed.\n");
return EXIT_FAILURE;
}
pid = fork ();
if (pid == (pid_t) 0)
{
close (mypipe[1]);
read_from_pipe (mypipe[0]);
return EXIT_SUCCESS;
}
else if (pid < (pid_t) 0)
{
fprintf (stderr, "Fork failed.\n");
return EXIT_FAILURE;
}
else
{
close (mypipe[0]);
write_to_pipe (mypipe[1]);
return EXIT_SUCCESS;
}
}
但是,我在运行此代码时似乎遇到了段错误。我有什么遗漏的吗?
最佳答案
一旦您创建了 test.txt
文件,它可能会正常工作。
至少在我的机器上修复了它。
在 C 语言中,您通常需要进行一些相当繁琐的错误检查才能健壮地编写程序。例如,您应该编写如下内容:
int read_from_pipe (int file) {
FILE *stream;
int c;
if((stream = fdopen (file, "r"))==NULL) goto err;
while ((c = fgetc (stream)) != EOF){
putchar (c);
}
if(ferror(stream)){ int er=errno; fclose (stream); errno=er; goto err; }
return 0;
err:
perror("read"); return -errno;
}
等等
测试文件的 fopen
行如下所示:
if(!(testfile = fopen("test.txt", "r"))) { perror("write"); return -errno; }
您可能会收到一条很好的“写入:没有这样的文件或目录”
消息。
关于c - 使用管道在进程之间发送字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37954850/