/* Copyright 2004 Sun Microsystems, Inc. ALL RIGHTS RESERVED Use of this software is authorized pursuant to the terms of the license found at http://developers.sun.com/berkeley_license.html Listing 5b. Example of a port being shared between processes Compile with Sun Studio 9: cc -o port_rcvfd listing5b_user.c Compile with gcc 3.4.1: gcc -o port_rcvfd listing5b_user.c Usage: ./port_rcvfd <# of user events> Usage example: `bash-2.05b$ ./port_sendfd 10 & sleep 4; ./port_rcvfd 10 10` */ #include #include #include #include #include #include #include #include #include #define PORT_PIPE "/tmp/port_attach" /* Child collect events from parent process created by running port_sendfd */ int main(int argc, char *argv[]){ int error; int index; int ret; int counter; int number_of_user_events = 0; port_event_t *portbuf; struct timespec timeout; int port; uint_t nwait; int fd; int timeout_value = 0; struct strrecvfd recbuf; if(argv[1] != NULL) number_of_user_events = atoi(argv[1]); if(argv[2] != NULL) timeout_value = atoi(argv[2]); if(argc != 3 || number_of_user_events < 1 || timeout_value < 1){ printf("Usage: %s <# of user events> \n", argv[0]); exit (-1); } printf("child: use pipe to retrieve port file descriptor\n"); fd = open(PORT_PIPE, O_RDWR); if(fd == -1){ printf("child: Can not open the pipe %s\n", PORT_PIPE); return (-1); } ret = ioctl(fd, I_RECVFD, &recbuf); if(ret == -1){ printf("child: I_RECVFD ioctl failed\n"); return (-1); } port = recbuf.fd; portbuf = (port_event_t *) calloc(number_of_user_events + 1, sizeof (port_event_t)); printf("child: wait %d secs for %d events from parent process\n", timeout_value, number_of_user_events); timeout.tv_sec = timeout_value; timeout.tv_nsec = 0; nwait = number_of_user_events/2; counter = 0; while(counter < number_of_user_events){ nwait = (number_of_user_events - counter)/ 2; ret = port_getn(port, portbuf, number_of_user_events, &nwait, &timeout); if(ret == -1){ error = errno; printf("child: port_getn error(errno=%d), nwait=%lld\n", error, nwait); if(error != ETIME) break; } if(nwait == 0) continue; counter += nwait; printf("child: %d user-defined events detected\n", nwait); for(index = 0;index < nwait; index++){ printf("%d: port = %d, events = %d, userp = 0x%x\n", index, port, portbuf[index].portev_events, portbuf[index].portev_user); } } printf("child: end\n"); }