进程间通信----无名管道
#include <unistd.h>
#include <stdio.h>
int main(void)
{
int fd[2];
pid_t pid;
pipe(fd);
pid=fork();
if(pid < 0){
printf("pid error\n");
return 0;
}
else if(pid > 0){
printf("父进程写:\n");
char a[100];
sprintf(a,"asdfg\n");
write( fd[1],a,sizeof(a));
close( fd[0] );
close( fd[1] );
}
else
{
sleep(7);
printf("This is child process.\n");
char b[100];
read( fd[0], b, sizeof(b));
printf( "read pipe: %s\n", b );
close( fd[0] );
close( fd[1] );
}
waitpid( pid, NULL, 0 );
return 0;
}
进程间通信----有名管道
mkfifo()本质是将普通文件定义为管道文件。
已存在时error会被置为EEXIST。
格式:
if((mkfifo(FIFO_NAME,0777)<0)&&(errno!=EEXIST))
{
fd=open(FIFO_NAME,O_RDONLY);
write(fd,buf,length-1);
unlink(FIFO_NAME);
close(fd);
}
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#define FIFO_NAME "/tmp/myfifo"
main()
{
int fd,length,running=1;
char w_buf[50],buf[50];
int w_num;
while(running)
{
if((mkfifo(FIFO_NAME,0777)<0)&&(errno!=EEXIST))
{
printf("cannot create fifo...\n");
exit(1);
}
fd=open(FIFO_NAME,O_WRONLY);
printf("pls input something\n");
fgets(buf,50,stdin);
if(strcmp(buf,"end\n")==0)
running=0;
length=strlen(buf);
w_num=write(fd,buf,length-1);
printf("length is %d\n",w_num);
}
sleep(2);
}
read.c
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#define FIFO_NAME "123"
main()
{
char r_buf[50];
int fd,running=1;
int r_num;
while(running)
{
if((mkfifo(FIFO_NAME,0777)<0)&&(errno!=EEXIST))
{
printf("cannot create fifo...\n");
exit(1);
}
fd=open(FIFO_NAME,O_RDONLY);
if(fd==-1)
{
printf("open %s for read error\n");
exit(1);
}
r_num=read(fd,r_buf,50);
r_buf[r_num]='\0';
if(strcmp(r_buf,"end")==0)
running=0;
printf(" %d bytes read:%s\n",r_num,r_buf);
}
unlink(FIFO_NAME);
}
信号(内核发给进程的通知)
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
static int alarm_fired = 0;
void ouch(int sig)
{
alarm_fired = 1;
}
int main()
{
signal(SIGALRM, ouch);
alarm(5);
pause();
if(alarm_fired == 1)
printf("Receive a signal %d\n", SIGALRM);
exit(0);
}