通过C中的管道读取/写入 [英] Read / Write through a pipe in C

查看:374
本文介绍了通过C中的管道读取/写入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天开始在C语言中使用pipe(),fork()和exec(),但是现在遇到了一个问题:

I started today working with pipe() and fork() and exec() in C, and I now have a problem:

主程序创建两个管道和叉子.子进程对另一个程序执行exec(),该程序现在只是一个从stdin读取,与它的父进程通信并通过stdout其他结果写入的测试程序.主程序应该能够接收数据,与SQLite 3数据库进行通信并使用管道返回数据.问题的这一部分已解决,管道已正确打开和关闭,并且可以进行通讯.

The main program, creates two pipes and forks. The child process does an exec() to another program that now is only a test program which reads from stdin, communicates with its parent and writes through stdout ther results. The main program is supposed to recive data, communicate with a SQLite 3 database and return data using pipes. This part of the problem is solved, the pipes are open and closed properly and there's communication.

然后问题是,在子进程(通过exec()调用的那个进程)中,在某一点上,我有这个问题:

Then the problem is, in the child process (the one which is called with exec()) in a certain point, I have this:

printf("Strid sent: %s\n", strid);
write(4,strid,sizeof(strid));

printf("Str sent: %s\n", str);
write(4,str,sizeof(str));

家长应该正确阅读这一部分内容:

And the parent should be reading properly with this part:

read(select[0],strid, sizeof(strid));
printf("Strid recived: %s\n",strid);
int id = atoi(strid);
printf("Id recived: %d\n",id);

read(select[0],buffer, sizeof(buffer));
printf("Buffer recived: %s\n",buffer);

但是我认为那些printf是:

But what I recive whith those printf is:

Strid sent: 1
Str sent: start
Strid recived: 1
Id recived: 1
Buffer recived: 7� (and other strange characters)

如您所见,问题出在第二条命令的接收上(并且该部分被照原样复制,没有其他代码被放入其中.)

As you can see, the problem is in the receiving of the second command (and that part is copied as is, there's no other code into it).

我也不得不说,将str的"buffer"变量声明为char buffer [20],并且在read()之前没有使用过

I have to say too that "buffer" variable, which recives str, is declared as char buffer[20] and has not been used before the read()

提前谢谢!

推荐答案

读取后,您需要在打印之前在末尾添加0字节,类似

After read, you need to add terminating 0 byte at the end, before printing, something like

int len = read(select[0], buffer, sizeof(buffer) - 1);
if (len < 0) {
    perror("read error");
} else {
    buffer[len] = 0;
    printf("Buffer recived: %s\n", buffer);
}

重要的是,通读 read 的手册页,或者实际上使用任何功能之前的手册页...

So, imporant thing, read through man page of read, or actually man page of any function before you use it...

或者,使用某些 stdio.h 函数,该函数自己添加终止0的字符串,可能是 fgets (如果可以逐行读取).

Alternatively, use some stdio.h function, which adds string terminating 0 themselves, probably fgets if reading line by line is ok.

这篇关于通过C中的管道读取/写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆