open_read_write
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int fd;
char buf[32] = "hello";
int n_write;
int n_read;
char readBuf[32];
memset(readBuf,'\0',32);
fd = open("./FILE",O_RDWR|O_CREAT,0600);
if(fd == -1)
{
perror("open");
exit(1);
}
n_write = write(fd,&buf,strlen(buf));
lseek(fd,SEEK_SET,0);
n_read =read(fd,&readBuf,strlen(buf));
printf("read %dBite form write: %s\n",n_read,readBuf);
close(fd);
return 0;
}
进程的创建—父进程与子进程
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
int main()
{
pid_t pid;
pid = vfork();
int fd;
int cnt = 0;
char buf[128] = "hello huang hong lei";
char readBuf[128];
fd = open("./file",O_RDWR|O_CREAT,0600);
if(pid == 0)
{
while(1)
{
write(fd,&buf,sizeof(buf));
sleep(1);
cnt++;
if(cnt == 5)
{
printf("child exit\n");
exit(0);
}
printf("cnt:%d\n",cnt);
}
}
}
无名管道pipe函数
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int fd[2];
int reg;
pid_t pid;
reg = pipe(fd);
char readBuf[32] = {
'\0'};
char buf[32] = "hello huang hong lei";
if(reg == -1)
{
perror("pipe");
exit(1);
}
pid = fork();
if(pid == 0)
{
close(fd[0]);
write(fd[1],&buf,sizeof(buf));
exit(0);
}
if(pid > 0)
{
wait(NULL);
close(fd[1]);
read(fd[0],&readBuf,sizeof(readBuf));
printf("form child :%s\n",readBuf);
}
close(fd[0]);
close(fd[1]);
return 0;
}
有名管道FIFO
写:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
int main()
{
int fd;
char buf[32] = "hello huang hong lei";
fd = open("file",O_WRONLY);
write(fd,&buf,sizeof(buf));
close(fd);
return 0;
}
读:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
int main()
{
int fd;
char buf[32] = {
'\0'};
if(mkfifo("file", 0666) < 0 && errno!=EEXIST)
{
perror("Create FIFO Failed");
}
fd = open("file",O_RDONLY);
read(fd,&buf,sizeof(buf));
printf("from write: %s\n",buf);
close(fd);
return 0;
}
信号Singal
#include <signal.h>
#include <stdio.h>
void handler(int sig)
{
if(sig == SIGINT)
{
printf("ctrl C\n");
}
}
int main()
{
signal(SIGINT,handler);
while(1)
{
printf("hello\n");
sleep(1);
}
return 0;
}