Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <sys/stat.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- #include <stdlib.h>
- #include <string.h>
- #include <ctype.h>
- #include <time.h>
- static int p2cpipe[2]; /* This descriptor is used for parent to child comm. */
- static int c2ppipe[2]; /* This descriptor is used for child to parenpipt comm. */
- static char text[255];
- struct tm *info;
- char buff[255];
- /**
- * This is the parent process. It will act as the parent when executing.
- * @param pid This is the process ID of the spawned child process.
- */
- void parentProcess(pid_t pid, int numRuns) {
- int index;
- // Initialize the buffer.
- memset(&text[0], 0, 255);
- // CLose the pipes we will not be needing.
- close(p2cpipe[0]);
- close(c2ppipe[1]);
- /* Must be the master process. */
- for (index = 0; index < numRuns; index++) {
- time_t rawtime;
- time(&rawtime);
- info = gmtime(&rawtime);
- strftime(buff, sizeof(buff), "GMT: %a %b %d %T %Y", info);
- printf("%s\n", buff);
- /* Write to the pipe. */
- write(p2cpipe[1], &info, sizeof(info));
- // Wait for the child process to respond to our message.
- read(c2ppipe[0], &text[0], 255);
- printf("%s\n", &text[0]);
- sleep(1);
- }
- }
- /**
- * This is the child process. It will perform the role of the child in the program.
- */
- void childProcess(int numRuns, int offset) {
- /* PID = 0. Must be the slave process. */
- // Initialize the buffer to be empty.
- memset(&text[0], 0, 255);
- // Close the pipes this process will not need.
- close(p2cpipe[1]);
- close(c2ppipe[0]);
- for (int i = 0; i < numRuns; i++) {
- /* Read from the pipe. */
- read(p2cpipe[0], &info, sizeof(info));
- info->tm_hour += offset;
- mktime(info);
- /* Now that there is text, print it out. */
- strftime(buff, sizeof(buff), "%a %b %d %T %Y", info);
- char offset_formatted[255];
- if(offset < 0) {
- sprintf(offset_formatted, "- %i", (offset*-1));
- } else {
- sprintf(offset_formatted, "+ %i", offset);
- }
- printf("GMT %s: %s\n", offset_formatted, buff);
- // Write the data into the pipe so that the parent receives it.
- write(c2ppipe[1], "OK", 255);
- }
- }
- int main(int argc, char*argv[]) {
- /* the process id for the given set of processes. */
- pid_t pid;
- /* Initialize the pipes between processes. Note: We need two pipes because a pipe is unidirectional when defined this way.*/
- pipe(p2cpipe);
- pipe(c2ppipe);
- /* Fork the new processes. */
- pid = fork();
- if (pid < 0) {
- printf("Fork failed.\n");
- exit(-1);
- } else if (pid == 0) {
- /* PID = 0. Must be the slave process. */
- childProcess(atoi(argv[1]), atoi(argv[2]));
- } else {
- parentProcess(pid, atoi(argv[1]));
- /* Wait for the child process to complete. */
- waitpid(pid, NULL, 0);
- }
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement