Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <sys/types.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdbool.h>
- #include <stdint.h>
- #include <signal.h>
- #define UnusedArg(x) ((void)x)
- #define osErrorFatal(userMsg) osErrorFatalImpl(userMsg, __FILE__, __func__, __LINE__)
- #define osAssert(expr, userMsg) \
- do { \
- if(!(expr))\
- osErrorFatal(userMsg);\
- } while(0)
- #define PIPE_RD 0
- #define PIPE_WR 1
- void osErrorFatalImpl(const char* userMsg, const char* fileName, const char* functionName, const int lineNumber) {
- perror(userMsg);
- fprintf(stderr, "File: %s\nFunction: %s\nLine: %d\n", fileName, functionName, lineNumber);
- exit(EXIT_FAILURE);
- }
- int main(int argc, char** argv) {
- osAssert(2 == argc, "./2 path/to/file.");
- int pipeFd1[2], pipeFd2[2];
- osAssert(-1 != pipe(pipeFd1), "Failed to make pipe.");
- osAssert(-1 != pipe(pipeFd2), "Failed to make pipe.");
- int fd = open(argv[1], O_RDONLY);
- osAssert(-1 != fd, "Failed to open file.");
- pid_t childPid = fork();
- osAssert(-1 != childPid, "Fork failed.");
- if(childPid > 0) { //parent
- close(pipeFd1[PIPE_RD]);
- close(pipeFd2[PIPE_WR]);
- unsigned bufLen = 1 << 13;
- char* buf = malloc(bufLen);
- osAssert(NULL != buf, "Failed to allocate memory for bufer.");
- int bytesRead = 0;
- osAssert(-1 != (bytesRead = read(fd, buf, bufLen)), "Failed to read from file.");
- buf[bytesRead] = 0;
- // printf("%s\n", buf);
- osAssert(-1 != write(pipeFd1[PIPE_WR], buf, bytesRead), "Failed to write from parent.");
- osAssert(-1 != wait(NULL), "Failed to wait for child.");
- osAssert(-1 != (bytesRead = read(pipeFd2[PIPE_RD], buf, bufLen)), "Failed to read from child.");
- buf[bytesRead - 1] = 0;
- printf("After tr:\n%s\n", buf);
- close(pipeFd1[PIPE_WR]);
- close(pipeFd2[PIPE_RD]);
- free(buf);
- }
- else { //child
- close(pipeFd2[PIPE_RD]);
- close(pipeFd1[PIPE_WR]);
- unsigned bufLen = 1 << 13;
- char* buf = malloc(bufLen);
- osAssert(NULL != buf, "Failed to allocate memory for bufer.");
- int bytesRead = 0;
- osAssert(-1 != (bytesRead = read(pipeFd1[PIPE_RD], buf, bufLen)), "Failed to read from file.");
- buf[bytesRead] = 0;
- int fdSave = dup(STDOUT_FILENO);
- osAssert(-1 != dup2(pipeFd2[PIPE_WR], STDOUT_FILENO), "Failed to replace STDOUT_FILENO.");
- char* cmd = malloc(bufLen+15);
- osAssert(NULL != cmd, "Failed to allocate memory for system command.");
- sprintf(cmd, "echo \"%s\" | tr a A", buf);
- int returnSys = system(cmd);
- osAssert(returnSys != -1, "System failed.");
- osAssert(EXIT_SUCCESS == WEXITSTATUS(returnSys), "System did not exit with EXIT_SUCCESS.");
- osAssert(-1 != dup2(fdSave, STDOUT_FILENO), "Failed to return STDOUT_FILENO.");
- close(pipeFd1[PIPE_RD]);
- close(pipeFd2[PIPE_WR]);
- free(cmd);
- free(buf);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement