【发布时间】:2017-07-07 15:34:59
【问题描述】:
我想将一个字符从一个 c 程序发送到一个 shell 程序。我正在使用命名管道在需要时发送字母“a”。我应该只需要打开一次管道。这是一个例子:
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
int main(){
int fd;
mkfifo("/tmp/test", 0666);
fd = open("/tmp/test", O_WRONLY);
printf("Opened\n");
char * a = "a";
while(1){
printf("Writing to pipe...\n");
write(fd,a,1);
sleep(1);
}
}
shell 会根据需要多次执行此命令...
head -c 1 /tmp/test
问题是在一个头之后,即使没有人在那里,c 也会源源不断地流入管道。
我注意到 open() 会阻塞,直到有人在另一端。如何告诉 write() 在有人阅读之前阻止?
我宁愿在 write() 上使用此功能而不是 read(),因为我认为为每个请求打开文件会产生很多开销。
谢谢!
更新
这就是我在 Java 中处理它的方式,它会等到有人在这个管道上监听它才会继续。也许只是因为它是一种高级语言。
public static void writeToPipe(int val, String pipename){
try{
pipe_out = new PrintStream("/tmp/" + pipename);
}catch(Exception e){
System.out.println("Could not open a pipe for output!");
e.printStackTrace();
}
try{
pipe_out.println(val);
}catch(Exception e){
System.out.println("Could not write to pipe!");
e.printStackTrace();
}
try{
pipe_out.close();
}catch(Exception e){
System.out.println("Could not close the output pipe!");
e.printStackTrace();
}
}
更新 #2 - 这是解决方案
这是我根据 David 的想法编写的代码,它很粗糙,但它确实有效。我没有检查命名管道是否存在,只是阻止它退出。
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/wait.h>
#include <stdlib.h>
int main(int argc, char **argv){
mkfifo("/tmp/test", 0666);
while(1){
int fd, status;
if ((fd = open ("/tmp/test", O_WRONLY)) == -1) {
perror ("open failed");
return 1;
}
printf("Opened Pipe\n");
char a = 'a';
int f = fork();
if(f == -1){
perror("fork");
exit(1);
}else if(f == 0){
//This is by the child process
if (write (fd, &a, 1) == -1) {
close(fd);
perror ("open failed");
return 1;
}
}else{
//This is the parent process
int w = waitpid(f, &status, WUNTRACED | WCONTINUED);
if (w == -1){
perror("waitpid");
exit(EXIT_FAILURE);
}
}
}
}
【问题讨论】:
-
这可能是一个缓冲的东西。如果您向管道写入了足够多的数据,则写入将阻塞,直到有人开始从中读取(或者写入可能会返回 EAGAIN 或类似内容)。