Skip to content

Instantly share code, notes, and snippets.

@smoser
Created September 29, 2011 21:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smoser/1251979 to your computer and use it in GitHub Desktop.
Save smoser/1251979 to your computer and use it in GitHub Desktop.
test virFileOpen
/*
test-virFileOpen.c
This mimics libvirt/src/lxc/lxc_controller.c in lxcControllerRun
gcc -o test-virFileOpen test-virFileOpen.c
mkdir d
sudo ./test-virFileOpen d
We get varied results. Sometimes this passes, sometimes it fails.
*/
#define _XOPEN_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sys/mount.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <errno.h>
#define PATH_MAX 4096
int virFileOpenTtyAt(const char *ptmx,
int *ttymaster,
char **ttyName,
int rawmode)
{
int rc = -1;
if ((*ttymaster = open(ptmx, O_RDWR|O_NOCTTY|O_NONBLOCK)) < 0) {
printf("open failed\n");
goto cleanup;
}
printf("opened %s to %i ptsname=%s\n", ptmx, *ttymaster, ptsname(*ttymaster));
if (unlockpt(*ttymaster) < 0) {
printf("unlockpt failed\n");
goto cleanup;
}
if (grantpt(*ttymaster) < 0) {
printf("grantpt failed (%i)\n", errno);
perror("grantpt");
goto cleanup;
}
if (rawmode) {
struct termios ttyAttr;
if (tcgetattr(*ttymaster, &ttyAttr) < 0) {
printf("tcgetattr failed\n");
goto cleanup;
}
cfmakeraw(&ttyAttr);
if (tcsetattr(*ttymaster, TCSADRAIN, &ttyAttr) < 0) {
printf("tcsetattr failed\n");
goto cleanup;
}
}
if (ttyName) {
// if (VIR_ALLOC_N(*ttyName, PATH_MAX) < 0) {
if ((ttyName = malloc(PATH_MAX)) == 0) {
printf("failed malloc\n");
errno = ENOMEM;
goto cleanup;
}
if (ptsname_r(*ttymaster, *ttyName, PATH_MAX) < 0) {
printf("ptsname_r failed\n");
goto cleanup;
}
}
rc = 0;
cleanup:
if (rc != 0)
close(*ttymaster);
// VIR_FORCE_CLOSE(*ttymaster);
return rc;
}
int main(int argc, char* argv[]) {
char *devpts = argv[1];
char devptmx[4096];
int containerPty = -1;
char *containerPtyPath = NULL;
sprintf(devptmx, "%s/ptmx", devpts);
printf("devptmx=%s devpts=%s\n", devptmx, devpts);
if (mount("devpts", devpts, "devpts", 0,
"newinstance,ptmxmode=0666,mode=0620,gid=5") < 0) {
printf("mount of %s failed\n", devpts);
return(1);
}
if (virFileOpenTtyAt(devptmx,
&containerPty,
&containerPtyPath,
0) < 0) {
printf("virFileOpenTtyAt failed\n");
close(containerPty);
if(umount(devpts) != 0) { perror("umount"); printf("umount failed\n"); }
return(1);
}
close(containerPty);
if(umount(devpts) != 0) { perror("umount"); printf("umount failed\n"); }
printf("Everything seems good\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment