getspent、setspent和endspent運行出錯

下面這代碼本身沒有任何問題,只是運行時報了段錯誤。

 13 #include <shadow.h>  
 22 int main(int argc, char **argv)
 23 {
199     struct spwd *ptr = NULL;
200     char name[] = "jack";
201     setspent();
202     while ((ptr = getspent()) != NULL)
203         if (strcmp(name, ptr->sp_namp) == 0)
204             break;
205      
206     printf("%s %s\n", ptr->sp_namp, ptr->sp_pwdp);
207     ptr = getspent();
208     endspent();
209     printf("%s %s\n", ptr->sp_namp, ptr->sp_pwdp); 
}

下面是編譯執行結果:

jack@jxes-VirtualBox:~/samba_share/apue$ gcc test.c 
jack@jxes-VirtualBox:~/samba_share/apue$ ./a.out 
**Segmentation fault (core dumped)**

這三個函數(另外還有一個getspnam),它們操作的對像是/etc/shadow這個file,這個file是一個系統文件,主要用來記錄賬戶名、密文的密碼信息,以及有效時間信息,所以要操作這個文件得是root權限,所以上面錯誤是因爲執行a.out需要root權限,在ubuntu下可以用sudo執行root權限。

jack@jxes-VirtualBox:~/samba_share/apue$ gcc test.c 
jack@jxes-VirtualBox:~/samba_share/apue$ **sudo** ./a.out 
jack $6$02HyL64f$GKhyMKTwANuwIhwExRnY9Yn1sWDhf5K9ISBq95vqWrhggT7JAe40dFP18qzvYjdT8c7QgwKfCvFJk91qaK73U0
vboxadd !
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章