无名管道
#include
#include
#include
#define INPUT 0
#define OUTPUT 1
int main()
{
int file_pipe[2];
pid_t pid;
char buf[256];
int count_pipe;
pipe(file_pipe); //无名管道
if(!(pid = fork()))
{
printf("child output data!\n");
close(file_pipe[INPUT]);
write(file_pipe[OUTPUT], "aoyang", strlen("aoyang"));
exit(0);
}
else if(pid > 0)
{
printf("father input data!\n");
close(file_pipe[OUTPUT]);
count_pipe = read(file_pipe[INPUT], buf, sizeof(buf));
printf("%d bytes received from father: %s\n",count_pipe, buf);
}
return 0;
}
有名管道
mknod myfifo p
#include
void main()
{
FILE * in_file;
int count = 1;
char buf[80];
in_file = fopen("mypipe", "r");
if (in_file == NULL)
{
printf("Error in fdopen.\n");
exit(1);
}
while ((count = fread(buf, 1, 80, in_file)) > 0)
printf("received from pipe: %s\n", buf);
fclose(in_file);
}
#include
void main() {
FILE * out_file;
int count = 1;
char buf[80];
out_file = fopen("mypipe", "w");
if (out_file == NULL)
{
printf("Error opening pipe.");
exit(1);
}
sprintf(buf,"this is test data for the named pipe example\n");
fwrite(buf, 1, 80, out_file);
fclose(out_file);
}
信号量
#include
#include
union semun{
int val;
struct semid_ds *buf;
unsigned short *array;
struct seminfo *__buf;
};
int main()
{
key_t unique_key;
int id;
struct sembuf lock_it;
union semun options;
int i;
unique_key = ftok(".", 'a'); //生成关键字
id = semget(unique_key ,1, IPC_CREAT | IPC_EXCL | 0666);
printf("semaphone id =%d\n", id);
options.val = 1;
semctl(id, 0, SETVAL, options);
i = semctl(id, 0, GETVAL, 0);
printf("value of semaphore at index 0 is %d\n", i);
//
lock_it.sem_num = 0; /*设置哪个信号量*/
lock_it.sem_op = -1; /*定义操作*/
lock_it.sem_flg = IPC_NOWAIT; /*操作方式*/
if (semop(id, &lock_it, 1) == -1)
{
printf("can not lock semaphone.\n");
exit(1);
}
i = semctl(id, 0, GETVAL, 0);
printf("value of semaphore at index 0 is %d\n", i);
semctl(id, 0, IPC_RMID, 0);
return 0;
}
阅读(1096) | 评论(1) | 转发(1) |