当前位置: 技术问答>linux和unix
vfork中多进程间共享描述符的问题
来源: 互联网 发布时间:2015-08-19
本文导语: 这是主进程: int main() { int server_sockfd, client_sockfd; int server_len, client_len; struct sockaddr_in server_address; struct sockaddr_in client_address; sigset_t *sig_set, *oset; int lo = 1; if( (serve...
这是主进程:
int main()
{
int server_sockfd, client_sockfd;
int server_len, client_len;
struct sockaddr_in server_address;
struct sockaddr_in client_address;
sigset_t *sig_set, *oset;
int lo = 1;
if( (server_sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
printf("socket() error!n");
else printf("socket Number:%in", server_sockfd);
if( setsockopt(server_sockfd, SOL_SOCKET, SO_REUSEADDR, (char *) &lo, sizeof(lo)) != 0)
fprintf(stdout, "setsockopt errorn");
close_on_exec(server_sockfd);
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
server_address.sin_port = htons(5000);
server_len = sizeof(server_address);
if( bind(server_sockfd, (struct sockaddr *)&server_address, server_len) != 0)
fprintf(stdout, "bind error!n");
/* Create a connection queue */
if( listen(server_sockfd, 5) != 0)
fprintf(stdout, "listen() error!n");
/* Accept connection. */
while(1) {
pid_t pid;
fprintf(stdout, "server waiting...n");
client_len = sizeof(client_address);
client_sockfd = accept(server_sockfd,
(struct sockaddr *)&client_address, &client_len);
fprintf(stdout, "one client request for connecting!n");
/* creates child process and loop .the parent process will listen again */
if( (pid = vfork()) 2)
close(client_sockfd);
if ( execl("/bin/fd_deal", NULL)
int main()
{
int server_sockfd, client_sockfd;
int server_len, client_len;
struct sockaddr_in server_address;
struct sockaddr_in client_address;
sigset_t *sig_set, *oset;
int lo = 1;
if( (server_sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
printf("socket() error!n");
else printf("socket Number:%in", server_sockfd);
if( setsockopt(server_sockfd, SOL_SOCKET, SO_REUSEADDR, (char *) &lo, sizeof(lo)) != 0)
fprintf(stdout, "setsockopt errorn");
close_on_exec(server_sockfd);
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
server_address.sin_port = htons(5000);
server_len = sizeof(server_address);
if( bind(server_sockfd, (struct sockaddr *)&server_address, server_len) != 0)
fprintf(stdout, "bind error!n");
/* Create a connection queue */
if( listen(server_sockfd, 5) != 0)
fprintf(stdout, "listen() error!n");
/* Accept connection. */
while(1) {
pid_t pid;
fprintf(stdout, "server waiting...n");
client_len = sizeof(client_address);
client_sockfd = accept(server_sockfd,
(struct sockaddr *)&client_address, &client_len);
fprintf(stdout, "one client request for connecting!n");
/* creates child process and loop .the parent process will listen again */
if( (pid = vfork()) 2)
close(client_sockfd);
if ( execl("/bin/fd_deal", NULL)