add related info about deadlock and ipc: pipe, signal

This commit is contained in:
yuchen
2015-05-11 12:09:30 +08:00
parent e378ef4376
commit 026015ed25
5 changed files with 594 additions and 0 deletions

View File

@@ -0,0 +1,23 @@
#!/usr/bin/env python
# -*- encoding: utf8 -*-
import os, sys
print "I'm going to fork now - the child will write something to a pipe, and the parent will read it back"
r, w = os.pipe() # r,w是文件描述符, 不是文件对象
pid = os.fork()
if pid:
# 父进程
os.close(w) # 关闭一个文件描述符
r = os.fdopen(r) # 将r转化为文件对象
print "parent: reading"
txt = r.read()
os.waitpid(pid, 0) # 确保子进程被撤销
else:
# 子进程
os.close(r)
w = os.fdopen(w, 'w')
print "child: writing"
w.write("here's some text from the child")
w.close()
print "child: closing"
sys.exit(0)
print "parent: got it; text =", txt

View File

@@ -0,0 +1,43 @@
/*
* From
* [url]http://www.crasseux.com/books/ctutorial/Programming-with-pipes.html[/url]
* but changed to use fgets() instead of the GNU extension getdelim()
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *ps_pipe;
FILE *grep_pipe;
int bytes_read;
char buffer[100]; /* could be anything you want */
/* Open our two pipes
ls -a | grep pipe*
*/
ps_pipe = popen("/bin/ls -a", "r");
grep_pipe = popen("/bin/grep 'pipe*'", "w");
/* Check that pipes are non-null, therefore open */
if ((!ps_pipe) || (!grep_pipe)) {
fprintf(stderr, "One or both pipes failed.\n");
return EXIT_FAILURE;
}
bytes_read = 0;
while (fgets(buffer, sizeof(buffer), ps_pipe)) {
fprintf(grep_pipe, "%s", buffer);
bytes_read += strlen(buffer);
}
printf("Total bytes read = %d\n", bytes_read);
/* Close ps_pipe, checking for errors */
if (pclose(ps_pipe) != 0) {
fprintf(stderr, "Could not run 'ls', or other error.\n");
}
/* Close grep_pipe, cehcking for errors */
if (pclose(grep_pipe) != 0) {
fprintf(stderr, "Could not run 'grep', or other error.\n");
}
/* Exit! */
return 0;
}

View File

@@ -0,0 +1,28 @@
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
// Define the function to be called when ctrl-c (SIGINT) signal is sent to process
void
signal_callback_handler(int signum)
{
printf("Caught signal %d\n",signum);
// Cleanup and close up stuff here
// Terminate program
exit(signum);
}
int main()
{
// Register signal and signal handler
signal(SIGINT, signal_callback_handler);
while(1)
{
printf("Program processing stuff here.\n");
sleep(1);
}
return EXIT_SUCCESS;
}