How to get root permission inside Qt program?

2019-07-31 02:36发布

问题:

I need to create directory inside root directory using a qt widget application.

void Home::on_pushButton_clicked()
{
    system("mkdir /bin/mydir");
}

But,how to get root privilege before making folder inside /bin folder

回答1:

This article shows the necessary steps to get root privilages for your application, but it is only tested on Fedora. Here is the link



回答2:

A program cannot gain root privileges after it has been started; it is only permitted to (either temporarily or finally) drop privileges.

The best approach is usually to invoke a program such as gksudo or ksudo, which the system will invoke as root, at which point they temporarily drop root privileges, query the user for consent, close their connection to the GUI system, regain root privileges and execute the action.



回答3:

If you want your application to access some resources which requires root privilege, you have to run that application as root. e.g

sudo your_application_name

or login as root and then run that application.



回答4:

you can get root password using pkexec command inside programming like below:

 void Home::on_pushButton_clicked()
 {
    system("pkexec mkdir /bin/myDir");
 }

or you can try to using QProcess class, however for your purpose the pkexec is enough.