Sunteți pe pagina 1din 23

FIFOs & PIPEs

To send a simple string between two programs using pipes. Two different C programs communicating with each other. One program should send "Hi" and the other should receive it A regular pipe can only connect two related processes. It is created by a process and will vanish when the last process closes it.

FIFOs
A named pipe, also called a FIFO for its behavior, can be used to connect two unrelated processes and exists independently of the processes; meaning it can exist even if no one is using it. A FIFO is created using the mkfifo() library function.

Writer.c
#include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> int main() { int fd; char * myfifo = "/tmp/myfifo"; /* create the FIFO (named pipe) */ mkfifo(myfifo, 0666); /* write "Hi" to the FIFO */ fd = open(myfifo, O_WRONLY); write(fd, "Hi", sizeof("Hi")); close(fd); /* remove the FIFO */ unlink(myfifo); return 0; }

Reader.c #include <fcntl.h> #include <stdio.h> #include <sys/stat.h> #include <unistd.h> #define MAX_BUF 1024 int main() { int fd; char * myfifo = "/tmp/myfifo"; char buf[MAX_BUF]; /* open, read, and display the message from the FIFO */ fd = open(myfifo, O_RDONLY); read(fd, buf, MAX_BUF); printf("Received: %s\n", buf); close(fd); return 0; }

PIPEs
#include <stdio.h> #include <unistd.h> #include <sys/types.h> int main(void) { int fd[2], nbytes; pid_t childpid; char string[] = "Hello, world!\n"; char readbuffer[80]; pipe(fd); if((childpid = fork()) == -1) { perror("fork"); exit(1); }

if(childpid == 0) { /* Child process closes up input side of pipe */ close(fd[0]); /* Send "string" through the output side of pipe */ write(fd[1], string, (strlen(string)+1)); exit(0); } else { /* Parent process closes up output side of pipe */ close(fd[1]); /* Read in a string from the pipe */ nbytes = read(fd[0], readbuffer, sizeof(readbuffer)); printf("Received string: %s", readbuffer); } return(0); }

Shared Memory
process1 #include<iostream.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include<unistd.h> #define SHMSZ 1024

int write(int *b) { char c; int shmid; key_t key; int *shm; char *s; /* * We'll name our shared memory segment * "5678". */ key = 5678; /*

* Create the segment. */ if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0) { cerr<<"shmget"; exit(1); } /* * Now we attach the segment to our data space. */ if ((shm = (int *)/*(char *)*/shmat(shmid, 0, 0)) == /*(char *)*/(int *) -1) { cerr<<"shmat"; exit(1); } /* * Now put some things into the memory for the * other process to read. */ // s = shm; int i; for (i=0; i<=1000; i++,shm++) *shm = i; *b=0; cout<<"write is complited"<<endl; cout<<*b<<endl; return(*b); } main() { char c; int shmid; key_t key; static int *b; key = 5679; /* * Create the one bit segment. */ if ((shmid = shmget(key, 1, IPC_CREAT | 0666)) < 0) { cerr<<"shmget"; exit(1); } /* * Now we attach the segment to our data space. */ if ((b = ( int *)shmat(shmid, 0, 0)) == (int *) -1) { cerr<<"shmat"; exit(1);

} cout<<*b<<endl; while(1) { if(*b==1) { write(b); } else wait(); } }

process2 #include<iostream.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include<unistd.h> #define SHMSZ int read(int *b) { char c; int shmid; key_t key; int *shm; char *s; /* * We'll name our shared memory segment * "5678". */ key = 5678; /* * Create the segment. */ if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0) { cerr<<"shmget"; exit(1); } /* * Now we attach the segment to our data space. */ if ((shm = (int *)shmat(shmid, 0, 0)) == (int *) -1) { cerr<<"shmat"; exit(1); } 1024

/*now read what the server put in the memory. */ int i; for (i=0; i<=1000; i++,shm++) cout<<*shm<<endl; cout<<"read is completed"<<endl; *b=1; cout<<"*b is "<<*b<<endl; return(*b); } main() {

char c; int shmid; key_t key; static int *b; key = 5679; /* * Create the one bit segment. */ if ((shmid = shmget(key, 1, IPC_CREAT | 0666)) < 0) { cerr<<"shmget"; exit(1); } /* * Now we attach the segment to our data space. */ if ((b = (int *)shmat(shmid, 0, 0)) == (int *) -1) { cerr<<"shmat"; exit(1); } cout<<" *b is "<<*b<<endl; while(1) { if(*b==0) { read(b); } else wait(); } } If u want to compile these programs then open two terminals and run process1.cpp and process2.cpp at a time. Then u will observe that if one is writing to the shared memory then another will be waiting vice versa.

Semaphores
This is a Semaphore example in C. Every thread created will first try to acquire the semaphore lock and then start printing numbers. After printing is done lock is left so other threads can continue their job. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <pthread.h> #include <semaphore.h> #define MAX_THREAD 100 typedef struct { int start,end; } param; sem_t mysem; void *count(void *arg){ sem_wait(&mysem); int i =0; param *p=(param *)arg; printf("\nprintfrom %d to %d\n",p->start,p->end); for(i =p->start ; i< p->end ; i++){ printf(" i = %d",i);sleep(1); } sem_post(&mysem); return (void*)(1); } int main(int argc, char* argv[]) { if ( sem_init(&mysem,0,1) ) { perror("init"); } int n,i; pthread_t *threads; param *p;

34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66.

if (argc != 2) { printf ("Usage: %s n\n",argv[0]); printf ("\twhere n is no. of threads\n"); exit(1); } n=atoi(argv[1]); if ((n < 1) || (n > MAX_THREAD)) { printf ("arg[1] should be 1 - %d.\n",MAX_THREAD); exit(1); } threads=(pthread_t *)malloc(n*sizeof(*threads)); p=(param *)malloc(sizeof(param)*n); /* Assign args to a struct and start thread */ for (i=0; i<n; i++) { p[i].start=i*100; p[i].end=(i+1)*100; pthread_create(&threads[i],NULL,count,(void *)(p+i)); } printf("\nWait threads\n"); sleep(1); /* Wait for all threads. */ int *x = malloc(sizeof(int)); for (i=0; i<n; i++) { pthread_join(threads[i],(void*)x); } free(p); exit(0); }

Message Queues
A message queue program that shows a client server implementation this is the receiver program using Message Queues

#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h>

struct my_msg_st { long int my_msg_type; char some_text[BUFSIZ]; };

int main(void) { int running = 1; int msgid; struct my_msg_st some_data; long int msg_to_recieve = 0;

/* Let us set up the message queue */ msgid = msgget((key_t)1234, 0666 | IPC_CREAT);

if (msgid == -1) {

perror("msgget failed with error"); exit(EXIT_FAILURE); }

/* Then the messages are retrieved from the queue, until an end message is * encountered. lastly the message queue is deleted */

while(running) { if (msgrcv(msgid, (void *)&some_data, BUFSIZ, msg_to_recieve, 0) == -1) { perror("msgcrv failed with error"); exit(EXIT_FAILURE); } printf("You wrote: %s", some_data.some_text); if (strncmp(some_data.some_text, "end", 3) == 0) { running = 0; } }

if (msgctl(msgid, IPC_RMID, 0) == -1) { perror("msgctl(IPC_RMID) failed"); exit(EXIT_FAILURE); }

exit(EXIT_SUCCESS); }

IPC: when you create a message queue, it doesn't go away until you destroy it. All the processes that have ever used it can quit, but the queue will still exist. A good practice is to use the ipcs command to check if any of your unused message queues are just floating around out there. You can destroy them with the ipcrm command, which is preferable to getting a visit from the sysadmin telling you that you've grabbed every available message queue on the system.
7.1. Where's my queue?

Let's get something going! First of all, you want to connect to a queue, or create it if it doesn't exist. The call to accomplish this is the msgget() system call:
int msgget(key_t key, int msgflg); msgget() returns the message queue ID on success, or -1 on failure (and it sets errno, of

course.) The arguments are a little weird, but can be understood with a little brow-beating. The first, key is a system-wide unique identifier describing the queue you want to connect to (or create). Every other process that wants to connect to this queue will have to use the same key. The other argument, msgflg tells msgget() what to do with queue in question. To create a queue, this field must be set equal to IPC_CREAT bit-wise OR'd with the permissions for this queue. (The queue permissions are the same as standard file permissionsqueues take on the user-id and group-id of the program that created them.) A sample call is given in the following section.
7.2. "Are you the Key Master?"

What about this key nonsense? How do we create one? Well, since the type key_t is actually just a long, you can use any number you want. But what if you hard-code the number and some other unrelated program hardcodes the same number but wants another queue? The solution is to use the ftok() function which generates a key from two arguments:
key_t ftok(const char *path, int id);

Ok, this is getting weird. Basically, path just has to be a file that this process can read. The other argument, id is usually just set to some arbitrary char, like 'A'. The ftok() function uses information about the named file (like inode number, etc.) and the id to generate a probablyunique key for msgget(). Programs that want to use the same queue must generate the same key, so they must pass the same parameters to ftok().

Finally, it's time to make the call:


#include <sys/msg.h> key = ftok("/home/beej/somefile", 'b'); msqid = msgget(key, 0666 | IPC_CREAT);

In the above example, I set the permissions on the queue to 666 (or rw-rw-rw-, if that makes more sense to you). And now we have msqid which will be used to send and receive messages from the queue.
7.3. Sending to the queue

Once you've connected to the message queue using msgget(), you are ready to send and receive messages. First, the sending: Each message is made up of two parts, which are defined in the template structure struct msgbuf, as defined in sys/msg.h:
struct msgbuf { long mtype; char mtext[1]; };

The field mtype is used later when retrieving messages from the queue, and can be set to any positive number. mtext is the data this will be added to the queue. "What?! You can only put one byte arrays onto a message queue?! Worthless!!" Well, not exactly. You can use any structure you want to put messages on the queue, as long as the first element is a long. For instance, we could use this structure to store all kinds of goodies:
struct pirate_msgbuf { long mtype; /* must be positive */ struct pirate_info { char name[30]; char ship_type; int notoriety; int cruelty; int booty_value; } info; };

Ok, so how do we pass this information to a message queue? The answer is simple, my friends: just use msgsnd():

int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg); msqid is the message queue identifier returned by msgget(). The pointer msgp is a pointer to the data you want to put on the queue. msgsz is the size in bytes of the data to add to the queue (not counting the size of the mtype member). Finally, msgflg allows you to set some optional flag parameters, which we'll ignore for now by setting it to 0.

When to get the size of the data to send, just subtract the sizeof(long) (the mtype) from the sizeof() the whole message buffer structure:
struct cheese_msgbuf { long mtype; char name[20]; int type; float yumminess; }; /* calculate the size of the data to send: */ int size = sizeof(struct cheese_msgbuf) - sizeof(long);

(Or if the payload is a simple char[], you can use the length of the data as the message size.) And here is a code snippet that shows one of our pirate structures being added to the message queue:
#include <sys/msg.h> #include <stddef.h> key_t key; int msqid; struct pirate_msgbuf pmb = {2, { "L'Olonais", 'S', 80, 10, 12035 } }; key = ftok("/home/beej/somefile", 'b'); msqid = msgget(key, 0666 | IPC_CREAT); /* stick him on the queue */ msgsnd(msqid, &pmb, sizeof(struct pirate_msgbuf) - sizeof(long), 0);

Aside from remembering to error-check the return values from all these functions, this is all there is to it. Oh, yeah: note that I arbitrarily set the mtype field to 2 up there. That'll be important in the next section.

7.4. Receiving from the queue

Now that we have the dreaded pirate Francis L'Olonais stuck in our message queue, how do we get him out? As you can imagine, there is a counterpart to msgsnd(): it is msgrcv(). How imaginative. A call to msgrcv() that would do it looks something like this:
#include <sys/msg.h> #include <stddef.h> key_t key; int msqid; struct pirate_msgbuf pmb; /* where L'Olonais is to be kept */ key = ftok("/home/beej/somefile", 'b'); msqid = msgget(key, 0666 | IPC_CREAT); /* get him off the queue! */ msgrcv(msqid, &pmb, sizeof(struct pirate_msgbuf) - sizeof(long), 2, 0);

There is something new to note in the msgrcv() call: the 2! What does it mean? Here's the synopsis of the call:
int msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg);

The 2 we specified in the call is the requested msgtyp. Recall that we set the mtype arbitrarily to 2 in the msgsnd() section of this document, so that will be the one that is retrieved from the queue. Actually, the behavior of msgrcv() can be modified drastically by choosing a msgtyp that is positive, negative, or zero:
msgtyp

Effect on msgrcv() Retrieve the next message on the queue, regardless of its mtype. Get the next message with an mtype equal to the specified msgtyp. Retrieve the first message on the queue whose mtype field is less than or equal to the absolute value of the msgtyp argument.

Zero Positive Negative

So, what will often be the case is that you'll simply want the next message on the queue, no matter what mtype it is. As such, you'd set the msgtyp parameter to 0.
7.5. Destroying a message queue

There comes a time when you have to destroy a message queue. Like I said before, they will stick around until you explicitly remove them; it is important that you do this so you don't waste system resources. Ok, so you've been using this message queue all day, and it's getting old. You want to obliterate it. There are two ways:
1. Use the Unix command ipcs to get a list of defined message queues, then use the command ipcrm to delete the queue. 2. Write a program to do it for you.

Often, the latter choice is the most appropriate, since you might want your program to clean up the queue at some time or another. To do this requires the introduction of another function: msgctl(). The synopsis of msgctl() is:
int msgctl(int msqid, int cmd, struct msqid_ds *buf);

Of course, msqid is the queue identifier obtained from msgget(). The important argument is cmd which tells msgctl() how to behave. It can be a variety of things, but we're only going to talk about IPC_RMID, which is used to remove the message queue. The buf argument can be set to NULL for the purposes of IPC_RMID. Say that we have the queue we created above to hold the pirates. You can destroy that queue by issuing the following call:
#include <sys/msg.h> . . msgctl(msqid, IPC_RMID, NULL);

And the message queue is no more.


7.6. Sample programs, anyone?

For the sake of completeness, I'll include a brace of programs that will communicate using message queues. The first, kirk.c adds messages to the message queue, and spock.c retrieves them. Here is the source for kirk.c:

#include #include #include #include #include #include #include

<stdio.h> <stdlib.h> <errno.h> <string.h> <sys/types.h> <sys/ipc.h> <sys/msg.h>

struct my_msgbuf { long mtype; char mtext[200]; }; int main(void) { struct my_msgbuf buf; int msqid; key_t key; if ((key = ftok("kirk.c", 'B')) == -1) { perror("ftok"); exit(1); } if ((msqid = msgget(key, 0644 | IPC_CREAT)) == -1) { perror("msgget"); exit(1); } printf("Enter lines of text, ^D to quit:\n"); buf.mtype = 1; /* we don't really care in this case */ while(fgets(buf.mtext, sizeof buf.mtext, stdin) != NULL) { int len = strlen(buf.mtext); /* ditch newline at end, if it exists */ if (buf.mtext[len-1] == '\n') buf.mtext[len-1] = '\0'; if (msgsnd(msqid, &buf, len+1, 0) == -1) /* +1 for '\0' */ perror("msgsnd"); } if (msgctl(msqid, IPC_RMID, NULL) == -1) { perror("msgctl"); exit(1);

} return 0; }

The way kirk works is that it allows you to enter lines of text. Each line is bundled into a message and added to the message queue. The message queue is then read by spock. Here is the source for spock.c:
#include #include #include #include #include #include <stdio.h> <stdlib.h> <errno.h> <sys/types.h> <sys/ipc.h> <sys/msg.h>

struct my_msgbuf { long mtype; char mtext[200]; }; int main(void) { struct my_msgbuf buf; int msqid; key_t key; if ((key = ftok("kirk.c", 'B')) == -1) { perror("ftok"); exit(1); } /* same key as kirk.c */

if ((msqid = msgget(key, 0644)) == -1) { /* connect to the queue */ perror("msgget"); exit(1); } printf("spock: ready to receive messages, captain.\n"); for(;;) { /* Spock never quits! */ if (msgrcv(msqid, &buf, sizeof(buf.mtext), 0, 0) == -1) { perror("msgrcv"); exit(1); } printf("spock: \"%s\"\n", buf.mtext);

} return 0; }

Signals IPC:Interrupts and Signals: <signal.h>


In this section will look at ways in which two processes can communicate. When a process terminates abnormally it usually tries to send a signal indicating what went wrong. C programs (and UNIX) can trap these for diagnostics. Also user specified communication can take place in this way.

Signals are software generated interrupts that are sent to a process when a event happens. Signals can be synchronously generated by an error in an application, such as SIGFPE and SIGSEGV, but most signals are asynchronous. Signals can be posted to a process when the system detects a software event, such as a user entering an interrupt or stop or a kill request from another process. Signals can also be come directly from the OS kernel when a hardware event such as a bus error or an illegal instruction is encountered. The system defines a set of signals that can be posted to a process. Signal delivery is analogous to hardware interrupts in that a signal can be blocked from being delivered in the future. Most signals cause termination of the receiving process if no action is taken by the process in response to the signal. Some signals stop the receiving process and other signals can be ignored. Each signal has a default action which is one of the following:

The signal is discarded after being received The process is terminated after the signal is received A core file is written, then the process is terminated Stop the process after the signal is received

Each signal defined by the system falls into one of five classes:

Hardware conditions Software conditions Input/output notification Process control Resource control

Macros are defined in <signal.h> header file for common signals. These include:
SIGHUP 1 /* hangup */ SIGQUIT 3 /* quit */ SIGINT 2 /* interrupt */ SIGILL 4 /* illegal instruction */

SIGABRT 6 /* used by abort */ SIGALRM 14 /* alarm clock */ SIGCONT 19 /* continue a stopped process */ SIGCHLD 20 /* to parent on child stop or exit */

SIGKILL 9 /* hard kill */

Signals can be numbered from 0 to 31.

Sending Signals -- kill(),

raise()

There are two common functions used to send signals


int kill(int pid, int signal) - a system call that send a signal to a process, pid. If pid is

greater than zero, the signal is sent to the process whose process ID is equal to pid. If pid is 0, the signal is sent to all processes, except system processes.
kill() returns 0 for a successful call, -1 otherwise and sets errno accordingly. int raise(int sig) sends the signal sig to the executing program. raise() actually uses kill() to send the signal to the executing program: kill(getpid(), sig);

There is also a UNIX command called kill that can be used to send signals from the command line - see man pages. NOTE: that unless caught or ignored, the kill signal terminates the process. Therefore protection is built into the system. Only processes with certain access privileges can be killed off. Basic rule: only processes that have the same user can send/receive messages. The SIGKILL signal cannot be caught or ignored and will always terminate a process.

For examplekill(getpid(),SIGINT); would send the interrupt signal to the id of the calling process. This would have a similar effect to exit() command. Also ctrl-c typed from the command sends a SIGINT to the process currently being.

unsigned int alarm(unsigned int seconds) -- sends the signal SIGALRM to the invoking

process after seconds seconds.

Signal Handling -- signal()


An application program can specify a function called a signal handler to be invoked when a specific signal is received. When a signal handler is invoked on receipt of a signal, it is said to catch the signal. A process can deal with a signal in one of the following ways:

The process can let the default action happen The process can block the signal (some signals cannot be ignored) the process can catch the signal with a handler.

Signal handlers usually execute on the current stack of the process. This lets the signal handler return to the point that execution was interrupted in the process. This can be changed on a per-signal basis so that a signal handler executes on a special stack. If a process must resume in a different context than the interrupted one, it must restore the previous context itself

Receiving signals is straighforward with the function:


int (*signal(int sig, void (*func)()))() -- that is to say the function signal() will call the func functions if the process receives a signal sig. Signal returns a pointer to function func if successful or it returns an error to errno and -1 otherwise.

func() can have three values: SIG_DFL

-- a pointer to a system default function SID_DFL(), which will terminate the process upon receipt of sig.
SIG_IGN

-- a pointer to system ignore function SIG_IGN() which will disregard the sig action (UNLESS it is SIGKILL). A function address -- a user specified function.
SIG_DFL and SIG_IGN are defined in signal.h (standard library) header file.

Thus to ignore a ctrl-c command from the command line. we could do:
signal(SIGINT, SIG_IGN);

TO reset system so that SIGINT causes a termination at any place in our program, we would do:

signal(SIGINT, SIG_DFL);

sig_talk.c

Let us now write a program that communicates between child and parent processes using kill() and signal().
fork() creates the child process from the parent. The pid can be checked to decide whether it is

the child (== 0) or the parent (pid = child process id). The parent can then send messages to child using the pid and kill(). The child picks up these signals with signal() and calls appropriate functions. An example of communicating process using signals is sig_talk.c:
/* /* /* /* sig_talk.c --- Example of how 2 processes can talk */ to each other using kill() and signal() */ We will fork() 2 process and let the parent send a few */ signals to it`s child */ */

/* cc sig_talk.c -o sig_talk #include <stdio.h> #include <signal.h>

void sighup(); /* routines child will call upon sigtrap */ void sigint(); void sigquit(); main() { int pid; /* get child process */ if ((pid = fork()) < 0) { perror("fork"); exit(1); } if (pid == 0) { /* child */ signal(SIGHUP,sighup); /* set function calls */ signal(SIGINT,sigint); signal(SIGQUIT, sigquit); for(;;); /* loop for ever */ } else /* parent */ { /* pid hold id of child */ printf("\nPARENT: sending SIGHUP\n\n");

kill(pid,SIGHUP); sleep(3); /* pause for 3 secs */ printf("\nPARENT: sending SIGINT\n\n"); kill(pid,SIGINT); sleep(3); /* pause for 3 secs */ printf("\nPARENT: sending SIGQUIT\n\n"); kill(pid,SIGQUIT); sleep(3); } } void sighup() { } void sigint() { } void sigquit() { printf("My DADDY has Killed me!!!\n"); exit(0); } signal(SIGINT,sigint); /* reset signal */ printf("CHILD: I have received a SIGINT\n"); signal(SIGHUP,sighup); /* reset signal */ printf("CHILD: I have received a SIGHUP\n");

S-ar putea să vă placă și