如果多个进程之间需要协同处理某个任务时,这时就需要进程间的同步和数据交流。常用的进程间通信(IPC,InterProcess Communication)的方法有:
1.信号(sinal):信号是一种比较复杂的通信方式,用于通知接收进程某个事件已经发生。
2. 管道(Pipe):管道是一种半双工的通信方式,数据只能单向流动,而且只能在具有亲缘关系(通常是指父子进程关系)。
3.命名管道(fifo):命名管道(Named Pipe)也是半双工的通信方式,但是它允许无亲缘关系进程间的通信。
4. 命名socket或UNIX域socket(Named Socket或Unix Domain Socket):socket也是一种进程间通信机制,与其他通信机制不同的是,它可用于不同进程间的进程通信。
5. 信号量(Semaphore):信号量是一个计数器,可以用来控制多个进程对共享资源的访问。它常作为一种锁机制,防止某进程正在访问共享资源时,其他进程也访问该资源。因此,主要作为进程间以及同一进程内不同线程之间的同步手段。
6. 共享存储(Shared Memory):共享内存就是映射一段能被其他进程所访问的内存,这段共享内存由一个进程创建,但多个进程都可以访问。共享内存是最快的 IPC 方式,它是针对其他进程间通信方式运行效率低而专门设计的。它往往与其他通信机制,如信号两,配合使用,来实现进程间的同步和通信。
7. 消息队列(Message Queue):消息队列是由消息的链表,存放在内核中并由消息队列标识符标识。消息队列克服了信号传递信息少、管道只能承载无格式字节流以及缓冲区大小受限等缺点。
信号是Linux系统中用于进程之间通信或操作的一种机制,信号可以在任何时候发送给某一进程,而无须知道该进程的状态。下面是一个父子进程之间使用信号进行同步的例程:
#include
#include
#include
#include
#include
#include
#include
int g_child_stop = 0;
int g_parent_run = 0;
void sig_child(int signum)
{
if( SIGUSR1 == signum )
{
g_child_stop = 1;
}
}
void sig_parent(int signum)
{
if( SIGUSR2 == signum )
{
g_parent_run = 1;
}
}
int main(int argc, char **argv)
{
int pid;
int wstatus;
signal(SIGUSR1, sig_child);
signal(SIGUSR2, sig_parent);
if( (pid=fork()) < 0 )
{
printf("Create child process failure: %s\n", strerror(errno));
return -2;
}
else if(pid == 0)
{
/* child process can do something first here, then tell parent process to start running */
printf("Child process start running and send parent a signal\n");
kill(getppid(), SIGUSR2);
while( !g_child_stop )
{
sleep(1);
}
printf("Child process receive signal from parent and exit now\n");
return 0;
}
printf("Parent hangs up untill receive signal from child!\n");
while( !g_parent_run )
{
sleep(1);
}
/* parent process can do something here, then tell child process to exit */
printf("Parent start running now and send child a signal to exit\n");
kill(pid, SIGUSR1);
/* parent wait child process exit */
wait(&wstatus);
printf("Parent wait child process die and exit now\n");
return 0;
}
运行结果:
这个程序中,如果父进程先执行则进入到循环休眠等待状态,直到子进程给他发送信号之后才能跳出循环继续运行,这就可以确保子进程先执行它的任务。同样子进程在执行完成任务之后,就等待父进程给他发送信号之后才能退出,而父进程则通过调用wait()系统调用等待子进程退出后,父进程再退出。
管道是UNIX系统IPC的最古老的形式,所有的UNIX系统都提供此种通信机制 。下面编写一个例程,用于父进程给子进程方向发送数据。
#include
#include
#include
#include
#include
#include
#define MSG_STR "This message is from parent: Hello, child process!"
int main(int argc, char **argv)
{
int pipe_fd[2];
int rv;
int pid;
char buf[512];
int wstatus;
if( pipe(pipe_fd) < 0)
{
printf("Create pipe failure: %s\n", strerror(errno));
return -1;
}
if( (pid=fork()) < 0 )
{
printf("Create child process failure: %s\n", strerror(errno));
return -2;
}
else if(pid == 0)
{
/* child process close write endpoint, then read data from parent process */
close(pipe_fd[1]);
memset(buf, 0, sizeof(buf));
rv=read(pipe_fd[0], buf, sizeof(buf));
if(rv < 0 )
{
printf("Child process read from pipe failure: %s\n", strerror(errno));
return -3;
}
printf("Child process read %d bytes data from pipe: \"%s\"\n", rv, buf);
return 0;
}
/* parent process close read endpoint, then write data to child process */
close(pipe_fd[0]);
if( write(pipe_fd[1], MSG_STR, strlen(MSG_STR)) < 0)
{
printf("Parent process write data to pipe failure: %s\n", strerror(errno));
return -3;
}
printf("Parent start wait child process exit...\n");
wait(&wstatus);
return 0;
}
运行结果:
这个程序中,父进程创建管道之后fork(),这时子进程会继承父进程所有打开的文件描述符(包括管道),这时对于一个管道就有4个读写端(父子进程各有一对管道读写端),如果需要父进程往子进程里写数据,则需要在父进程中关闭读端,在子进程中关闭写端;而如果需要子线程往父进程中写数据,则可以在父进程关闭写端,然后子进程中关闭读端。
FIFO不同于管道之处在于它提供一个路径与之关联,以FIFO的文件形式存在于系统中。它在磁盘上有对应的节点,但没有数据块——换言之,只是拥有一个名字和相应的访问权限,通过mknode()系统调用或者mkfifo()函数来建立的。一旦建立,任何进程都可以通过文件名将其打开和进行读写,而不局限于父子进程,当然前提是进程对FIFO有适当的访问权。当不再被进程使用时,FIFO在内存中释放,但磁盘节点仍然存在。
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define FIFO_FILE1 ".fifo_chat1"
#define FIFO_FILE2 ".fifo_chat2"
int g_stop = 0;
void sig_pipe(int signum)
{
if(SIGPIPE == signum)
{
printf("get pipe broken signal and let programe exit\n");
g_stop = 1;
}
}
int main(int argc, char **argv)
{
int fdr_fifo;
int fdw_fifo;
int rv;
fd_set rdset;
char buf[1024];
int mode = 0;
if( argc != 2 )
{
printf("Usage: %s [0/1]\n", basename(argv[0]));
printf("This chat program need run twice, 1st time run with [0] and 2nd time with [1]\n");
return -1;
}
mode = atoi(argv[1]);
if( access(FIFO_FILE1 , F_OK) )
{
printf("FIFO file \"%s\" not exist and create it now\n", FIFO_FILE1);
mkfifo(FIFO_FILE1, 0666);
}
if( access(FIFO_FILE2 , F_OK) )
{
printf("FIFO file \"%s\" not exist and create it now\n", FIFO_FILE2);
mkfifo(FIFO_FILE2, 0666);
}
signal(SIGPIPE, sig_pipe);
if( 0 == mode )
{
printf("start open '%s' for read and it will blocked untill write endpoint opened...\n",
FIFO_FILE1);
if( (fdr_fifo=open(FIFO_FILE1, O_RDONLY)) < 0 )
{
printf("Open fifo[%s] for chat read endpoint failure: %s\n", FIFO_FILE1, strerror(errno));
return -1;
}
printf("start open '%s' for write...\n", FIFO_FILE2);
if( (fdw_fifo=open(FIFO_FILE2, O_WRONLY)) < 0 )
{
printf("Open fifo[%s] for chat write endpoint failure: %s\n", FIFO_FILE2, strerror(errno));
return -1;
}
}
else
{
printf("start open '%s' for write and it will blocked untill read endpoint opened...\n",
FIFO_FILE1);
if( (fdw_fifo=open(FIFO_FILE1, O_WRONLY)) < 0 )
{
printf("Open fifo[%s] for chat write endpoint failure: %s\n", FIFO_FILE1, strerror(errno));
return -1;
}
printf("start open '%s' for read...\n", FIFO_FILE2);
if( (fdr_fifo=open(FIFO_FILE2, O_RDONLY)) < 0 )
{
printf("Open fifo[%s] for chat read endpoint failure: %s\n", FIFO_FILE2, strerror(errno));
return -1;
}
}
printf("start chating with another program now, please input message now: \n");
while( !g_stop )
{
FD_ZERO(&rdset);
FD_SET(STDIN_FILENO, &rdset);
FD_SET(fdr_fifo, &rdset);
rv = select(fdr_fifo+1, &rdset, NULL, NULL, NULL);
if( rv <= 0 )
{
printf("Select get timeout or error: %s\n", strerror(errno));
continue;
}
if( FD_ISSET(fdr_fifo, &rdset) )
{
memset(buf, 0, sizeof(buf));
rv=read(fdr_fifo, buf, sizeof(buf));
if( rv < 0)
{
printf("read data from FIFO get errorr: %s\n", strerror(errno));
break;
}
else if( 0==rv )
{
printf("Another side of FIFO get closed and program will exit now\n");
break;
}
printf("<-- %s", buf);
}
if( FD_ISSET(STDIN_FILENO, &rdset) )
{
memset(buf, 0, sizeof(buf));
fgets(buf, sizeof(buf), stdin);
write(fdw_fifo, buf, strlen(buf));
}
}
}
四个步骤:
#include
#include
#include
#include
#include
#include
#include
#include
#define FTOK_PATH "/dev/zero"
#define FTOK_PROJID 0x22
union semun
{
int val;
struct semid_ds *buf;
unsigned short *arry;
};
int semaphore_init(void);
int semaphore_p(int semid);
int semaphore_v(int semid);
void semaphore_term(int semid);
int main(int argc, char **argv)
{
int semid;
pid_t pid;
int i;
if( (semid=semaphore_init()) < 0)
{
printf("semaphore initial failure: %s\n", strerror(errno));
return -1;
}
if( (pid=fork()) < 0)
{
printf("fork() failure: %s\n", strerror(errno));
return -2;
}
else if( 0 == pid)
{
printf("Child process start running and do something now...\n");
sleep(3);
printf("Child process do something over...\n");
semaphore_v(semid);
sleep(1);
printf("Child process exit now\n");
exit(0);
}
printf("Parent process P operator wait child process over\n");
semaphore_p(semid);
printf("Perent process destroy semaphore and exit\n");
sleep(2);
printf("Child process exit and ");
semaphore_term(semid);
return 0;
}
int semaphore_init(void)
{
key_t key;
int semid;
union semun sem_union;
if( (key=ftok(FTOK_PATH, FTOK_PROJID)) < 0 )
{
printf("ftok() get IPC token failure: %s\n", strerror(errno));
return -1;
}
semid = semget(key, 1, IPC_CREAT|0644);
if( semid < 0)
{
printf("semget() get semid failure: %s\n", strerror(errno));
return -2;
}
sem_union.val = 0;
if( semctl(semid, 0, SETVAL, sem_union)<0 )
{
printf("semctl() set initial value failure: %s\n", strerror(errno));
return -3;
}
printf("Semaphore get key_t[0x%x] and semid[%d]\n", key, semid);
return semid;
}
void semaphore_term(int semid)
{
union semun sem_union;
if( semctl(semid, 0, IPC_RMID, sem_union)<0 )
{
printf("semctl() delete semaphore ID failure: %s\n", strerror(errno));
}
return ;
}
int semaphore_p(int semid)
{
struct sembuf _sembuf;
_sembuf.sem_num = 0;
_sembuf.sem_op = -1;
_sembuf.sem_flg = SEM_UNDO;
if( semop(semid, &_sembuf, 1) < 0 )
{
printf("semop P operator failure: %s\n", strerror(errno));
return -1;
}
return 0;
}
int semaphore_v(int semid)
{
struct sembuf _sembuf;
_sembuf.sem_num = 0;
_sembuf.sem_op = 1;
_sembuf.sem_flg = SEM_UNDO; // IPC_NOWAIT SEM_UNDO
if( semop(semid, &_sembuf, 1) < 0 )
{
printf("semop V operator failure: %s\n", strerror(errno));
return -1;
}
return 0;
}
下面两个程序示例演示了不同进程中收发消息的过程,其中进程msgqueue_sender 往内核的消息队列里写入内容"Ping",而进程msgqueue_recver 则从消息队列里读出并打印该消息。
#include
#include
#include
#include
#include
#include
#include
#include
#define FTOK_PATH "/dev/zero"
#define FTOK_PROJID 0x22
typedef struct s_msgbuf
{
long mtype;
char mtext[512];
} t_msgbuf;
int main(int argc, char **argv)
{
key_t key;
int msgid;
t_msgbuf msgbuf;
int msgtype;
int i;
if( (key=ftok(FTOK_PATH, FTOK_PROJID)) < 0 )
{
printf("ftok() get IPC token failure: %s\n", strerror(errno));
return -1;
}
msgid = msgget(key, IPC_CREAT|0666);
if( msgid < 0)
{
printf("shmget() create shared memroy failure: %s\n", strerror(errno));
return -2;
}
msgtype = (int)key;
printf("key[%d] msgid[%d] msgypte[%d]\n", (int)key, msgid, msgtype);
for(i=0; i<4; i++)
{
msgbuf.mtype = msgtype;
strcpy(msgbuf.mtext,"Ping");
if( msgsnd(msgid, &msgbuf, sizeof(msgbuf.mtext), IPC_NOWAIT) < 0)
{
printf("msgsnd() send message failure: %s\n", strerror(errno));
break;
}
printf("Send message: %s\n", msgbuf.mtext);
sleep(1);
}
msgctl(msgid, IPC_RMID, NULL);
return 0;
}
#include
#include
#include
#include
#include
#include
#include
#include
#define FTOK_PATH "/dev/zero"
#define FTOK_PROJID 0x22
typedef struct s_msgbuf
{
long mtype;
char mtext[512];
} t_msgbuf;
int main(int argc, char **argv)
{
key_t key;
int msgid;
t_msgbuf msgbuf;
int msgtype;
int i;
if( (key=ftok(FTOK_PATH, FTOK_PROJID)) < 0 )
{
printf("ftok() get IPC token failure: %s\n", strerror(errno));
return -1;
}
msgid = msgget(key, IPC_CREAT|0666);
if( msgid < 0)
{
printf("shmget() create shared memroy failure: %s\n", strerror(errno));
return -2;
}
msgtype = msgtype = (int)key;
printf("key[%d] msgid[%d] msgypte[%d]\n", (int)key, msgid, msgtype);
for(i=0; i<4; i++)
{
memset(&msgbuf,0,sizeof(msgbuf));
if( msgrcv(msgid, &msgbuf, sizeof(msgbuf.mtext), msgtype, IPC_NOWAIT) < 0 )
{
printf("msgsnd() receive message failure: %s\n", strerror(errno));
break;
}
printf("Receive Message: %s\n", msgbuf.mtext);
sleep(1);
}
msgctl(msgid, IPC_RMID, NULL);
return 0;
}