CS计算机代考程序代写 60-256 System Programming: Pipes III

60-256 System Programming: Pipes III

Content

COMP-2560 System Programming:
Pipes III
Courtesy of Dr. B. Boufama

School of Computer Science University of Windsor

Instructor: Dr. Dan Wu

Pipes III
1

Content

Content

1
Review
man 7 pipe
man 7 fifo

// mknod fifoname p
man 3 mkfifo

Example 6 server / clients
Example 7 sendmessage / rcvmessage

Pipes III
2

Example 6

Example 6

The goal of the following example (example 6) is to write a client/server application where a server creates a child for each client. Then, the child creates a separate FIFO to send data to the client.

Pipes III
3

Example 6

Example 6: a client/server application…(Server part)

#include
#include // This is the server
#include
#include
#include
#include
#include

void child(pid_t client);

int main(int argc, char *argv[]){ int fd, status;
char ch; pid_t pid;
unlink(“/tmp/server”);
if(mkfifo(“/tmp/server”, 0777)){ perror(“main”);
exit(1);
}
while(1){
fprintf(stderr, “Waiting for a client\n”); fd = open(“/tmp/server”, O_RDONLY); fprintf(stderr, “Got a client: “); read(fd, &pid, sizeof(pid_t));
close(fd);
fprintf(stderr, “%ld\n”, pid); if(fork()==0)
child(pid);
else
waitpid(0, &status, WNOHANG);
}
}

Pipes III
4
Server1.c

Example 6

void child(pid_t pid){
char fifoName[100]; char newline = ’\n’; int fd, i;
sprintf(fifoName,”/tmp/fifo%d”, pid); unlink(fifoName);
mkfifo(fifoName, 0777);

fd = open(fifoName, O_WRONLY); for(i=0; i < 100; i++){ write(fd, fifoName, strlen(fifoName)); write(fd, &newline, 1); sleep(1); } close(fd); unlink(fifoName); exit(0); } Pipes III 5 Example 6 Example 6: a client/server application...(Client part) #include // This is the client
#include
#include
#include
#include

int main(int argc, char *argv[]){ // Client char ch, fifoName[100];
int fd; pid_t pid;
while((fd=open(“/tmp/server”, O_WRONLY))==-1){ fprintf(stderr, “trying to connect\n”); sleep(1);
}
pid = getpid();
write(fd, &pid, sizeof(pid_t)); close(fd); sprintf(fifoName,”/tmp/fifo%ld”, pid); sleep(1);
fd = open(fifoName, O_RDONLY); while(read(fd, &ch, 1) == 1)
fprintf(stderr, “%c”, ch); close(fd);
}

Pipes III
6
Client1.c

Content

Content

1
Example 7 sendmessage/rcvmessage

Note : open FIFO for RD/WR , or BOTH (in rcvmessage.c) , why?

Review textbook 15.5 pages 552-556)

Pipes III
7