Linux进程通信技术概览:popen与pclose函数详解.pptx

Linux进程通信技术概览:popen与pclose函数详解.pptx

第7章进程通讯

;主要内容

popen与pclose函数

管道通讯

共享内存

信号通讯

;?

?

;?

?

;?

?

;?

?

;?

?

;?

?

;?

?

;?

?

;#includestdio.h

#includestdlib.h

#includeunistd.h

#includestring.h

#includeerrno.h

#includesys/types.h

#includesys/wait.h

#defineBUF_SIZE255//messagebuffersize

intmain(intargc,char**argv)

{

charbuffer[BUF_SIZ+1];

intfd[2];

//receiveastringasparameter

if(argc!=2)

{

fprintf(stderr,Usage:%sstring\n\a,argv[0]);

exit(1);

}

//createpipeforcommunication

if(pipe(fd)!=0)

{

fprintf(stderr,Createpipeerror:%s\n\a,strerror(errno));

exit(1);

}

?

;

if(fork()==0)//inchildprocesswritemsgtopipe

{

close(fd[0]);

printf(Child%ldwritetopipe\n\a,getpid());

snprintf(buffer,BUF_SIZ,%s,argv[1]);

write(fd[1],buffer,strlen(buffer));

printf(Child%ldquit.\n\a,getpid());

}

else//inparentprocess,readmsgfrompipe

{

close(fd[1]);

printf(Parent%ldreadfrompipe\n\a,getpid());

memset(buffer,\0,BUF_SIZ+1);

read(fd[0],buffer,BUF_SIZ);

printf(Parent%ldread:\n%s\n,getpid(),buffer);

exit(1);

}

return0;

}

?

;?

?

;?

?

;?

?

;?

?

;?

?

;当打开一个FIFO时,非阻塞标志(O_NONBLOCK)产生下列影响:

如果没有说明O_NONBLOCK。只读打开会阻塞,直到写进程向管道中写入数据;类似,只写打开会阻塞,直到读进程从FIFO读取数据。

如果指定了O_NONBLOCK,则只读打开立即返回。但是,如果没有进程已经为读而打开一个FIFO,那么写进程打开将出错返回,其errno是ENXIO。

;FIFO相关出错信息:

EACCES(无存取权限)

EEXIST(指定文件不存在)

ENAMETOOLONG(路径名太长)

ENOENT(包含的目录不存在)

ENOSPC(文件系统剩余空间不足)

ENOTDIR(文件路径无效)

EROFS(指定的文件存在于只读文件系统中)

;?

?

;?

?

;每个IPC对象都有一个对应的数据结构,描述了其基本信息。

structipc_perm

{

uid_tuid;//所有者的有效用户id

gid_tgid;//所有者的有效组id

uid_tcuid;//创建者的有效用户id

gid_tcgid;//创建者的有效组id

mode_tmode;//对象的访问权限,与文件类似,不过没有可执行。

ulongseq;//对象的应用序号

key_tkey;

文档评论(0)

1亿VIP精品文档

相关文档