简体   繁体   中英

Permission denied when running compiled C program in Linux

I am attempting to write a simple program that calls git checkout -- . on a Github repo that would be a command line argument. I would like to call it like > clearRepo repoName . I keep all my repos in the same Github directory.

The code is as follows:

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

void print_error()
{
    fprintf(stderr, "Error executing: %s\n", strerror(errno));
    exit(EXIT_FAILURE);
}

void print_usage(char* this)
{
    printf("SYNTAX ERROR:\n%s [directoryName]\n", this);
    exit(EXIT_FAILURE);
}

int main(int argc, char **argv)
{ 
    if(argc != 2)
    {
        print_usage(argv[0]);
    }

    pid_t pid = fork();
    if (pid == 0)
    {   
        static char* params[] = {"git", "checkout",  "--",  ".", NULL};
        char s[50], s2[50];
        strcpy(s, "/home/myname/Documents/Github/");
        strcpy(s2, argv[1]);
        strcat(s, s2);
        printf("s: %s\n", s);
        int err = execv(s, params);
        if(err == -1)
        {
            print_error();
        }
        exit(127);
    }
    else
    {
        waitpid(pid, 0, 0);
    }

    return 0;
}

It compiles fine, but print_error() will spit out Error executing: Permission denied every time I run it. I am not too familiar with writing programs for Linux, so it is probably a simple mistake. Information on what I'm doing wrong is appreciated. Thanks.

The first argument you're passing to execv is a directory, but execv expects a program. The error "Permission denied" is slightly misleading, because there is no such thing as "permission to execute directories".

To change the current directory, call chdir . Then, call whichever one of the exec* functions you like to invoke git .

chmod u+x filename for changing file permission. If you want to checkout of a branch, but save the changes, use git stash. You can use git stash pop or git stash apply when you come back to the branch.

https://git-scm.com/docs/git-stash

Git commands and programs are quite tricky.

Follow these steps and you might debug your problem.

  1. Enter the git commands written in the program into a terminal and check if the logic actually works. (Suggested this as you said you were new to Linux)
  2. If it works, change the permission of your file by typing "chmod +x filename.extention".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM