aavivian 发表于 2012-07-30 17:33

linux C语言新手求助

本人linux C语言初学者(纯自学),很多问题不懂,求教各位前辈,为什么我的进程通讯测试程序中write和read函数都返回了-1?程序代码如下:
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main(void)
{
int pipefd;
int pipe_fd;
int length;
pid_t pid;
//char buf;
char kin,kout;
if(pipe(pipe_fd)!=0)
{
    printf("Error in pipe!");
    exit(0);
}
if((pid=fork())==-1)
{
    printf("Error in fork!\n");
    exit(0);
}
if(pid>0)
{
    close(pipe_fd);
    printf("This is the father process,please input characters!\n");
    gets(kin);
    // puts(kin);
    if(write(pipe_fd,kin,100)!=-1)
    {
      length=strlen(kin);
      printf("%d characters were write into the subprocess!\n",length);
      printf("%s were written to subprocess!\n",puts(kin));
    }
}
if(pid==0)
{
    close(pipe_fd);
    sleep(15);
    if(read(pipe_fd,kout,100)==-1)
    {
      length=strlen(kout);
      printf("%d characters written to subprocess!\n",length);
      printf("%s were written to subprocess!\n",puts(kout));
    }
}
}

xiyoulaoyuanjia 发表于 2012-07-30 22:00

#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main(void)
{
int pipefd;
int pipe_fd;
int length;
pid_t pid;
//char buf;
char kin,kout;
if(pipe(pipe_fd)!=0)
{
    printf("Error in pipe!");
    exit(0);
}
if((pid=fork())==-1)
{
    printf("Error in fork!\n");
    exit(0);
}
if(pid>0)
{
    close(pipe_fd);
    printf("This is the father process,please input characters!\n");
    gets(kin);
    // puts(kin);
    if(write(pipe_fd,kin,100)!=-1)
    {
      length=strlen(kin);
      printf("%d characters were write into the subprocess!\n",length);
   //   printf("%s were written to subprocess!\n",puts(kin));
    }
}
if(pid==0)
{
    close(pipe_fd);
    sleep(15);
    if(read(pipe_fd,kout,100)==-1)
    {
      length=strlen(kout);
      printf("%d characters written to subprocess!\n",length);
    //printf("%s were written to subprocess!\n",puts(kout));
    }
}
}:em03:

xiyoulaoyuanjia 发表于 2012-07-30 22:02

从你的用意来看可以把 printf改成 snprintf 函数 :em03:

aavivian 发表于 2012-07-31 02:15

这里的printf用的是不对,但现在最大的问题是write和read函数都返回了-1,写和读操作相当于全部失败了。

595528730 发表于 2012-07-31 10:12

字符串数组 没有 初始化   而且 读管道 和写管道针对的字符串输组不同

          # INCLUDE<STRING.H>
    可以用 MEMSET() 初始化 后       在写

xiyoulaoyuanjia 发表于 2012-08-01 00:47

pipe(pipe_fd)

aavivian 发表于 2012-08-01 14:25

回复 6# xiyoulaoyuanjia

实在抱歉,没有仔细看您回复的代码,忽略了这个参数传递的问题。说实话,这真不是个大问题,是我太马虎了。。。。。十分感谢前辈的提醒。


   

xiyoulaoyuanjia 发表于 2012-08-01 14:48

没关系!加油~~:em03:

crazy_snail 发表于 2012-08-25 23:12

if(read(pipe_fd,kout,100)==-1) ?
这句应该是 if(read(pipe_fd,kout,100)!=-1)才对吧

lichs 发表于 2012-08-30 17:55

经典的LINUX库函数手册,先看看这个
页: [1] 2
查看完整版本: linux C语言新手求助