基于服务器/客户端的管道(不是FIFO)文件权限检查器C ++

时间:2019-05-28 14:27:45

标签: c++ linux pipe client-server

我需要使用管道(不是FIFO)创建一个客户机/服务器程序,其中用户输入文件名和八进制权限,并且如果八进制文件权限与输入相同,则服务器返回“ YES”,否则返回“ NO”

我创建了2个管道,一个用于file_name,另一个用于八进制。我不知道如何在C ++中验证文件的属性。这是我制作的第一个管道程序,因此我认为我可能会遇到很多错误。感谢您的支持!

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

int main() 
{ 
    // We use two pipes 
    // First pipe to send input string from parent 
    // Second pipe to send concatenated string from child 

    int fd1[2];  // Used to store two ends of first pipe 
    int fd2[2];  // Used to store two ends of second pipe 

    char octal[7]; 
    char input_str[100]; 

    pid_t p; 

    if (pipe(fd1)==-1) 
    { 
        fprintf(stderr, "Pipe Failed" ); 
        return 1; 
    } 
    if (pipe(fd2)==-1) 
    { 
        fprintf(stderr, "Pipe Failed" ); 
        return 1; 
    } 

    scanf("%s", input_str); 
    scanf("%d", octal);
    p = fork(); 

    if (p < 0) 
    { 
        fprintf(stderr, "fork Failed" ); 
        return 1; 
    } 

    // Parent process 
    else if (p > 0) 
    { 
        char answear[100]; 

        close(fd1[0]);  // Close reading end of first pipe 

        // Write input string and close writing end of first 
        // pipe. 
        write(fd1[1], input_str, strlen(input_str)+1); 
    write(fd2[1], octal, 7); 
    close(fd2[1]);
        close(fd1[1]); 

        // Wait for child to send a string 
        wait(NULL); 

        // Read string from child, print it and close 
        // reading end. 
        read(fd2[0], answear, 100); 
        printf("The answear is %s\n", answear); 
        close(fd2[0]); 
    } 

    // child process 
    else
    { 
        close(fd1[1]);  // Close writing end of first pipe 
    close(fd2[1]);  // Close writing end of secound pipe
        // Read a string using first pipe 
        char file_name[100]; 
        read(fd1[0], file_name, 100); 
    // Read a int using secound pipe 
    int octal2[7];
    read(fd2[0], octal2, 7);

        // verify the octal permission of the file and give the result on the answear
        struct stat buf;  
    stat(file_name, &buf);
    int statchmod = buf.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
    if (statchmod == octal2[0])
        char answear[]="Totul e OK!"; //OK
    else
        chmod(file_name, S_IRWXU);
        char answear[]="Drepturile au fost modificate"; //not OK
        // Close both reading ends 
        close(fd1[0]); 
        close(fd2[0]); 


        // Write concatenated string and close writing end 
        write(fd2[1], answear, 100); 
        close(fd2[1]); 

        exit(0); 
    } 
} 

现在,如果更改了某些内容,结果将不会显示。它只显示“结果是”。

0 个答案:

没有答案