运行到open()函数卡住,怎么办?

caoshufengcao 2012-10-02 09:02:24
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <limits.h>
#include <unistd.h>
#include <fcntl.h>

int main()
{
int fd;
if((fd = open("fifo1",O_WRONLY)) < 0) {
perror("打开失败。");
exit(1);
}
printf("%d",fd);
write(fd,"nihao",6);
close(fd);
return 0;
}
路径是正确的,但是控制台没有任何输出。谷歌又跳不了页面,真急死俺啦。。。。
...全文
2106 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
阿晔sir 2012-10-05
  • 打赏
  • 举报
回复
对的[Quote=引用 6 楼 的回复:]
我解决啦。happy
2楼正解。
写进程会阻塞到有一个读进程来读这个FIFO管道。就是没有进程来读文件,则写进程会阻塞在open语句。
所以要两个程序一起运行就能看到结果啦。
附上两段代码,要一起运行,一读,一写。
一:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <unistd.h>
……
[/Quote]
阿晔sir 2012-10-05
  • 打赏
  • 举报
回复
为文件指针是 FILE *fp这是标准IO,用fopen打开文件返回文件指针,int fd是文件描述符,属于文件IO用open打开文件返回文件描述符,至于楼主的问题,你在printf("%d\n",fd);加了个\n,如果open没报错,估计是缓冲区问题[Quote=引用 5 楼 的回复:]
引用 4 楼 的回复:

引用楼主 的回复:
int fd;
if((fd = open……

弱弱的问一下:
有int fd;作为文件指针的吗?

应该是吧。我也刚开始学linuxC编程。
[/Quote]
大熊猫侯佩 2012-10-03
  • 打赏
  • 举报
回复
代码不是写出来的,是调出来的
caoshufengcao 2012-10-02
  • 打赏
  • 举报
回复
我解决啦。happy
2楼正解。
写进程会阻塞到有一个读进程来读这个FIFO管道。就是没有进程来读文件,则写进程会阻塞在open语句。
所以要两个程序一起运行就能看到结果啦。
附上两段代码,要一起运行,一读,一写。
一:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <unistd.h>
#include <fcntl.h>

int main()
{
int fd;
if((fd = open("/home/jimmy-cao/Workspaces/C/MAKEFIFO/fifo1",O_WRONLY)) < 0) {
perror("打开失败。");
exit(1);
}
printf("%d",fd);
write(fd,"nihao\n",6);
sleep(3);
close(fd);
return 0;
}


二:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <limits.h>
#include <unistd.h>

int main()
{
int fd;
int len;
char buf[PIPE_BUF];
if((fd = open("/home/jimmy-cao/Workspaces/C/MAKEFIFO/fifo1",O_RDONLY)) < 0) {
perror("打开失败。");
exit(1);
}
while((len = read(fd,buf,PIPE_BUF)) > 0) {
printf("%s",buf);
}
close(fd);
return 0;
}
两个一起运行哈。
caoshufengcao 2012-10-02
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 的回复:]

引用楼主 的回复:
int fd;
if((fd = open……

弱弱的问一下:
有int fd;作为文件指针的吗?
[/Quote]
应该是吧。我也刚开始学linuxC编程。
vc_qing 2012-10-02
  • 打赏
  • 举报
回复
[Quote=引用楼主 的回复:]
int fd;
if((fd = open……
[/Quote]
弱弱的问一下:
有int fd;作为文件指针的吗?
caoshufengcao 2012-10-02
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]

gdb一下,这么几行代码,应该很快搞定.
[/Quote]
明天学gdb。。。
qq120848369 2012-10-02
  • 打赏
  • 举报
回复
学linux开发请认真看书, 自己瞎摸既学不好又浪费时间。

O_NONBLOCK
When opening a FIFO with O_RDONLY or O_WRONLY set:

* If O_NONBLOCK is set, an open() for reading-only shall return without delay. An open() for writing-only shall return an error if no
process currently has the file open for reading.

* If O_NONBLOCK is clear, an open() for reading-only shall block the calling thread until a thread opens the file for writing. An open()
for writing-only shall block the calling thread until a thread opens the file for reading.
JiMoKuangXiangQu 2012-10-02
  • 打赏
  • 举报
回复
gdb一下,这么几行代码,应该很快搞定.

70,037

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧