转载:http://hbl369540604.blog.163.com/blog/static/203943010201231910252260/
void
{
int val;
if ( (val = fcntl(fd, F_GETFL, 0)) < 0)
{
printf("fcntl F_GETFL error");
exit(1);
}
val |= flags; /* turn on flags */
if (fcntl(fd, F_SETFL, val) < 0)
{
printf("fcntl F_SETFL error");
exit(1);
}
}
void
clr_fl(int fd, int flags)
{
int val;
if ((val = fcntl(fd, F_GETFL, 0)) == -1)
{
syslog(LOG_ERR, __FILE__, __LINE__,"fcntl() error : %s", strerror(errno));
exit(1);
}
val &= ~flags; /* turn flags off */
if (fcntl(fd, F_SETFL, val) == -1)
{
syslog(LOG_ERR, __FILE__, __LINE__,"fcntl() error : %s", strerror(errno));
exit(1);
}
return;
}
基于管道的父、子进程同步的例程
#include "apue.h"
static int pfd1[2], pfd2[2];
void TELL_WAIT(void)
{
//创建管道
if (pipe(pfd1) < 0 || pipe(pfd2) < 0)
err_sys("pipe error");
}
void TELL_PARENT(pid_t pid)
{
//把数据写进pfd2管道(写端-标准输出)
if (write(pfd2[1], "c", 1) != 1)
if (write(pfd2[1], "c", 1) != 1)
err_sys("write error");
}
void WAIT_PARENT(void)
{
char c;
//从pfd1管道(读端-标准输入)中读数据
if (read(pfd1[0], &c, 1) != 1)
err_sys("read error");
if (c != 'p')
err_quit("WAIT_PARENT:incorrect data");
}
void TELL_CHILD(pid_t pid)
{
if (write(pfd1[1], "p", 1) != 1)
err_sys("write error");
}
void WAIT_CHILD(void)
{
char c;
if (read(pid2[0], &c, 1) != 1)
err_sys("read error");
if ( c != 'c' )
err_quit("WAIT_CHILD: incorrent data");
}
信号版:
#include <sys/types.h>
#include <signal.h>
#include <unistd.h>
#include <stdio.h>
static void sig_usr(int signo)
{
sigflag = 1;
return;
}
void TELL_WAIT()
{
if (signal(SIGUSR1, sig_usr) == SIG_ERR)
printf("signal SIGUSR1 error\n");
if (signal(SIGUSR2, sig_usr) == SIG_ERR)
printf("signal SIGUSR2 error\n");
sigemptyset(&zeromask);
sigemptyset(&newmask);
sigaddset(&newmask, SIGUSR1);
sigaddset(&newmask, SIGUSR2);
/* block SIGUSR1 and SIGUSR2, and save current signal mask */
if (sigprocmask (SIG_BLOCK, &newmask, &oldmask) < 0)
printf("SIG_BLOCK error\n");
}
void TELL_PARENT(pid_t pid)
{
kill(pid, SIGUSR2); /* tell parent we are done */
}
void WAIT_PARENT()
{
while(sigflag == 0)
sigsuspend(&zeromask); /* wait for parent */
sigflag = 0;
/* reset signal mask */
if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0)
printf("SIG_SETMASK error\n");
}
void TELL_CHILD(pid_t pid)
{
kill(pid, SIGUSR1);
}
void WAIT_CHILD()
{
while(sigflag == 0)
sigsuspend(&zeromask); /* wait for parent */
sigflag = 0;
/* reset signal mask */
if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0)
printf("SIG_SETMASK error\n");
}