【Linux 编程基础】常见的系统调用

问题1

编写一个c程序,判断一份属于当前用户的文件是否可读可写,如果不可读或不可写则将其修改为可读可写。

#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>

int main(int argc, char** argv) {
    
    
    switch (argc) {
    
    
    default:
        puts("Argument ERROR\nUsage: getrwp [FILE]");
        return 0;
    case 2:
        if (open(argv[1], S_IRUSR | S_IWUSR) == -1) {
    
    
            perror("Open ERROR");
            if (chmod(argv[1], 0600) == -1) perror("Permission modification ERROR");
            else puts("Permission modification success.");
        }
        else printf("Open success: file %s can be read or written.\n", argv[1]);
        return 0;
    }
}

在这里插入图片描述

问题2

利用系统调用read()和write()实现类似cp命令的程序。

请考虑:1)目标文件不存在时,应新创建一个。2)目标文件已存在时,应删除掉原有内容。

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int main(int argc, char** argv) {
    
    
	struct stat sta;
	int fd1, fd2;
	void* buf;

    switch (argc) {
    
    
	default:
		puts("Argument ERROR\nUsage: copy [SOURCE] [DEST]");
		return 0;
	case 3:
		if (access(argv[2], F_OK) == -1) {
    
    
			fd1 = open(argv[1], O_RDONLY);
			stat(argv[1], &sta);
			buf = malloc(sta.st_size);
			read(fd1, buf, sta.st_size);
			fd2 = open(argv[2], O_CREAT | O_WRONLY);
			printf("Size of %s : %zd\n", argv[1], sta.st_size);
			printf("Written %zd bytes to %s\n", write(fd2, buf, sta.st_size), argv[2]);
			close(fd2);
			chmod(argv[2], sta.st_mode);
			close(fd1);
			free(buf);
		}
		else {
    
    
			fd2 = open(argv[2], O_TRUNC);
			close(fd2);
		}
		return 0;
	}
}

在这里插入图片描述

问题3

编写一个c程序,非阻塞式地从标准输入文件读取内容,当没有用户输入时每隔3秒循环打印“No input”,当有输入时打印用户的输入并且退出循环。

注意:自行考虑应该怎样实现间隔3秒的功能。

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

const size_t BUF_SIZE = 1 << 24;
const unsigned int delay = 3;

int main(int argc, char* argv[]) {
    
    
	void* buf = malloc(BUF_SIZE);
	
	int flags = fcntl(STDIN_FILENO, F_GETFL);
    if (flags < 0) {
    
    
        perror("fcntl ERROR");
        return -1;
    }

    flags |= O_NONBLOCK;
    int ret = fcntl(STDIN_FILENO, F_SETFL, flags);
    if (ret < 0) {
    
    
	    perror("fcntl ERROR");
        return -1;
    }
	
	for (;;) {
    
    
		ssize_t n = read(STDIN_FILENO, buf, BUF_SIZE);
		if (n < 0) {
    
    
			if (errno = EAGAIN) puts("No input");
			else perror("Read ERROR");
		}
		else {
    
    
			write(STDOUT_FILENO, buf, n);
			return 0;
		}
		sleep(delay);
	}
}

在这里插入图片描述

おすすめ

転載: blog.csdn.net/COFACTOR/article/details/115537957
おすすめ