Skip to content

Instantly share code, notes, and snippets.

@hamadu
Last active September 6, 2017 13:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hamadu/d0bf15759f9562edba37530d97313d20 to your computer and use it in GitHub Desktop.
Save hamadu/d0bf15759f9562edba37530d97313d20 to your computer and use it in GitHub Desktop.
pipe
#include <unistd.h>
#include <stdio.h>
int main(int argc, char* argv[]) {
int pipefd[2];
pipe(pipefd);
int readFd = pipefd[0];
int writeFd = pipefd[1];
pid_t result = fork();
if (result == 0) {
char data[100];
for (int i = 0 ; i < 100 ; i++) {
data[i] = (char)('a' + (i % 26));
}
write(writeFd, data, 100);
} else {
char buf[5];
while (1) {
int num = read(readFd, buf, 5);
if (num == 0) {
break;
}
printf("%s\n", buf);
}
}
return 0;
}
#include <unistd.h>
#include <stdio.h>
int main(int argc, char* argv[]) {
int pipefd[2];
pipe(pipefd);
int readFd = pipefd[0];
int writeFd = pipefd[1];
pid_t result = fork();
if (result == 0) {
dup2(writeFd, STDOUT_FILENO);
close(readFd);
close(writeFd);
execl("/bin/ls", "al", (char *)NULL);
} else {
close(writeFd);
char buf[5];
while (1) {
int num = read(readFd, buf, 5);
if (num == 0) {
break;
}
printf("%s\n", buf);
}
}
return 0;
}
#include <unistd.h>
#include <stdio.h>
int swapcase(int ch) {
if ('a' <= ch && ch <= 'z') {
return 'A' + (ch - 'a');
} else if ('A' <= ch && ch <= 'Z') {
return 'a' + (ch - 'A');
} else {
return ch;
}
}
int main(int argc, char* argv[]) {
FILE *reader = popen("/bin/ls -al", "r");
while (1) {
int ch = fgetc(reader);
if (ch == EOF) {
break;
}
fputc(swapcase(ch), stdout);
}
pclose(reader);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment