|
楼主 |
发表于 2007-5-21 21:54:06
|
显示全部楼层
因为只能传个int值给子进程,似乎还不够好,下面一个程序用共享内存的机制,实现传更多的数据给子进程。debian sid 编译运行通过。- #include <unistd.h>
- #include <signal.h>
- #include <stdio.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- #include <sys/ipc.h>
- #include <sys/shm.h>
- #include <stdlib.h>
- #include <fcntl.h>
- /* ERROR PRINT*/
- #define STD_FUNC "Standard function "
- #define SIG_STOP_CHILD SIGRTMIN+1
- #define BUFSIZE 4096
- int main()
- {
- pid_t pid;
- sigset_t newmask;
- int rcvd_sig;
- siginfo_t info;
- char tmpnm[L_tmpnam] = "";
- if( NULL == tmpnam(tmpnm)) {
- perror( STD_FUNC "tmpnamm failed:");
- exit(-1);
- }
- int fd = open(tmpnm, O_CREAT | O_EXCL);
- if( -1 == fd) {
- perror( STD_FUNC "open failed:");
- exit(-1);
- }
- key_t shk = ftok(tmpnm, 'X');
- if( -1 == shk) {
- perror( STD_FUNC "ftok failed:");
- exit(-1);
- }
- int shm_id = shmget(shk, BUFSIZE+1, IPC_CREAT | IPC_EXCL);
- if ( -1 == shm_id) {
- perror( STD_FUNC "shmget failed:");
- exit( -1);
- }
-
- if ((pid = fork()) == 0) { /*Child*/
- sigemptyset(&newmask);
- sigaddset(&newmask, SIG_STOP_CHILD);
- sigprocmask(SIG_BLOCK, &newmask, NULL);
- while (1) {
- rcvd_sig = sigwaitinfo(&newmask, &info);
- if (rcvd_sig == -1) {
- perror("sigusr: sigwaitinfo");
- _exit(1);
- }
- else {
- char * shm_buf = (char *)shmat(shm_id, NULL, 0);
- if( (char *)-1 == shm_buf) {
- perror( STD_FUNC"shmat failed:");
- exit(-1);
- }
- printf("Signal %d, value %d string "%s" received from parent\n",
- rcvd_sig, info.si_value.sival_ptr, shm_buf);
- shmdt( shm_buf);
- _exit(0);
- }
- }
- }
- else { /* Parent */
- sigval_t sval;
- sval.sival_int = 1;
- char * shm_buf = (char *)shmat(shm_id, NULL, 0);
- if( (char *)-1 == shm_buf) {
- perror( STD_FUNC "shmat failed:");
- exit(-1);
- }
- sprintf( shm_buf, "%s", "Hello World!");
- int stat;
- sleep(1);
- sigqueue(pid, SIG_STOP_CHILD, sval);
- pid = wait(&stat);
- printf("Child exit status = %d\n", WEXITSTATUS(stat));
- shmdt( shm_buf);
- shmctl(shm_id, IPC_RMID, NULL);
- close(fd);
- _exit(0);
- }
- }
复制代码 |
|