Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.6 kB
2
Indexable
Never
TW1 Pipes

#include <sys/wait.h> /* wait */
#include <stdio.h>
#include <stdlib.h> /* exit functions */
#include <unistd.h> /* read, write, pipe, _exit */
#include <string.h>
#define ReadEnd 0
#define WriteEnd 1
void report_and_exit(const char* msg) {
perror(msg);
exit(-1); /** failure **/
}
int main() {
int pipeFDs[2]; /* two file descriptors */
char buf; /* 1-byte buffer */
const char* msg = "Nature's first green is gold\n"; /* bytes to
write */
if (pipe(pipeFDs) < 0) report_and_exit("pipeFD");
pid_t cpid = fork(); /* fork a child
process */
if (cpid < 0) report_and_exit("fork"); /* check for
failure */
if (0 == cpid) { /*** child ***/ /* child process
*/
close(pipeFDs[WriteEnd]); /* child reads,
doesn't write */
while (read(pipeFDs[ReadEnd], &buf, 1) > 0) /* read until
end of byte stream */
write(STDOUT_FILENO, &buf, sizeof(buf)); /* echo to the
standard output */
close(pipeFDs[ReadEnd]); /* close the
ReadEnd: all done */
_exit(0); /* exit and
notify parent at once */
}
else { /*** parent ***/
close(pipeFDs[ReadEnd]); /* parent
writes, doesn't read */
write(pipeFDs[WriteEnd], msg, strlen(msg)); /* write the
bytes to the pipe */
close(pipeFDs[WriteEnd]); /* done writing:
generate eof */
wait(NULL); /* wait for
child to exit */
exit(0); /* exit normally
*/
}
return 0;
}

TW1 Message q

// C Program for Message Queue (Writer Process)
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MAX 10
// structure for message queue
struct mesg_buffer {
long mesg_type;
char mesg_text[100];
} message;
int main()
{
key_t key;
int msgid;
// ftok to generate unique key
key = ftok("progfile", 65);
// msgget creates a message queue
// and returns identifier
msgid = msgget(key, 0666 | IPC_CREAT);
message.mesg_type = 1;
printf("Write Data : ");
fgets(message.mesg_text,MAX,stdin);
// msgsnd to send message
msgsnd(msgid, &message, sizeof(message), 0);
// display the message
printf("Data send is : %s \n", message.mesg_text);
return 0;
}
// C Program for Message Queue (Reader Process)
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
// structure for message queue
struct mesg_buffer {
long mesg_type;
char mesg_text[100];
} message;
int main()
{
key_t key;
int msgid;
// ftok to generate unique key
key = ftok("progfile", 65);
// msgget creates a message queue
// and returns identifier
msgid = msgget(key, 0666 | IPC_CREAT);
// msgrcv to receive message
msgrcv(msgid, &message, sizeof(message), 1, 0);
// display the message
printf("Data Received is : %s \n",
message.mesg_text);
// to destroy the message queue
msgctl(msgid, IPC_RMID, NULL);
return 0;
}