您的位置:首页 > 其它

Concurrent Programming with Processes

2013-12-25 15:19 204 查看
Applications that use application-level concurrency are known as concurrent programs. Modern operating systems provide three basic approaches for building concurrent
programs: processes, I/O multiplexing and threads.
The simplest way to build a concurrent programs is with processes, using familiar functions such as fork, exec, and waitpid. For example,
a natural approach for building a concurrent server is to accept client connection requests in the parent, and then create a new child process to service each new client.
There are several important points to make about this server:
1. First, servers typically run for long periods of time, so we must include a SIGCHLD handler that reaps zombie children.

2. Second, the parent and the child must close their respective copies of connfd.

3. Finally, because of the reference count in the socket's file table entry, the connection to the client will not be terminated until both the parent's and child's copies of connfd are closed.
From these, the code for a concurrent echo server based on processes is showed below.

// SIGCHLD signal handler
void sigchld_handler(int sig)
{
while (waitpid(-1, 0, WNOHANG) > 0)
;
return;
}

int main(int argc, char **argv)
{
if (argc != 2) {
fprintf(stderr, "usage: %s <port>\n", argv[0]);
exit(0);
}
int port = atoi(argv[1]);
socklen_t clientlen = sizeof(struct sockaddr_in);
struct sockaddr_in clientaddr;

signal(SIGCHLD, sigchld_handler);
int listenfd = open_listenfd(port);
while (1) {
int connfd = accept(listenfd, (SA *) &clientaddr, &clientlen);
if (fork() == 0) {
close(listenfd); // Child closes its listening socket
echo(connfd); 	  // Child services client
close(connfd);   // Child closes connection with client
exit(0); 		  // Child exits
}
close(connfd); // Parent closes connected socket (important!)
}
}

Processes provide a clean sharing model where descriptors are shared and user address spaces are
not. Having separate address spaces for processes is both an advantage and a disadvantage. It is impossible for one process to accidentally overwrite the virtual memory of another process, which eliminates a lot of confusing failures—an obvious advantage.

On the other hand, separate address spaces make it more difficult for processes to share state information. To share information, they must use explicit IPC (interprocess
communication) mechanisms. Another disadvantage of process-based designs is that they tend to be slower because the overhead for process control and IPC is high.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: