XShmGetImage fails without any error displayed - x11

I have tried below simple program to use XShmGetImage to get the desktop image.
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xutil.h>
#include <X11/extensions/XShm.h>
#include <X11/extensions/Xfixes.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int main(int argc, const char *argv[])
{
int screen;
Window root;
Display* display;
XImage* img,
int shm=0;
XShmSegmentInfo shminfo;
/* My Desktop Screen Resolution */
int width=1360;
int height=768;
display = XOpenDisplay(getenv("DISPLAY"));
shm = XShmQueryExtension(display);
if ( shm) {
printf ("Ha... QueryExtension Successful..\n");
int scr = XDefaultScreen (display);
printf ("\n Screen Number is %d ", scr);
img = XShmCreateImage (display, DefaultVisual(display, scr),
DefaultDepth ( display, scr),
ZPixmap,
NULL,
&shminfo,
width,
height);
printf ("\n Bytes Per Line %d ", img->bytes_per_line);
shminfo.shmid = shmget (IPC_PRIVATE, img->bytes_per_line * img->height, IPC_CREAT | 0777);
if ( shminfo.shmid == -1 ) {
printf ("\n Can not get the shared Memory ...");
} else {
printf ("\n Greate I am able to get shared memory..");
}
shminfo.shmaddr = img->data =shmat (shminfo.shmid, 0,0);
shminfo.readOnly = False;
if (!XShmAttach (display, &shminfo)) {
printf ("\n i am unable to attach now..");
} else {
printf ("\n Super.. i am able to attach Shared memory to extension ");
}
if ( !XShmGetImage (display, RootWindow(display, DefaultScreen(display)), img, 0,0, AllPlanes)){
printf ("\n Now you should have your image in XImage");
} else {
printf ("\n Ooops.. Something wrong.");
}
}
Output:
Ha... QueryExtension Successful..
Screen Number is 0
Bytes Per Line 5440
Greate I am able to get shared memory..
Super.. i am able to attach Shared memory to extension
Ooops.. Something wrong.
Unfortunately, XShmGetImage fails, and no information is displayed. Please help.

There was a blunder from my side. Actually, it works properly, and I misinterpreted the return value of XShmGetImage API().
The correct one is
if ( !XShmGetImage (display, RootWindow(display, DefaultScreen(display)), img, 0,0, AllPlanes)){
printf ("\n Ooops.. Something wrong.");
} else {
printf ("\n Now you should have your image in XImage");
}

Related

Reading and printing last N characters

I have a program that I want to use to read a file and output its last N characters (could be 50 or whatever that I have coded). From my piece of code, I get output that is question marks in diamond boxes,(unsupported unicode?)
I'm using lseek to set the cursor, could someone please assist me?
int main(int argc,char *argv[]){
int fd; //file descriptor to hold open info
int count=0; //to hold value of last 200th char number
char ch; //holds read char
char* outputString = "The file does not exist!\n";
if(!access("myFile.txt",F_OK)==0){
write(2,outputString,strlen(outputString));
exit(1);
}
fd = open("myFile.txt",O_RDONLY| O_NONBLOCK);
int ret = lseek(fd,200,SEEK_END); //get position of the last 200th item
while (ret!=0) {
write(1, &ch,1);
ret--;
}
close(fd);
return(0);
}
I don't want to use <stdio.h> functions so I'm using the file descriptors not making a FILE* object.
I slightly modified your attempt. The lseek(fd, 200, SEEK_END) seeks the file 200 characters past the end of file. If you want to read last 200 character from a file, you need to seek to 200 character to end of file, ie lseek(fd, -200, SEEK_END).
I places some comments in code to help explaining.
// please include headers when posting questions on stackoverflow
// It makes it way easier to reproduce and play with the code from others
#include <unistd.h>
#include <error.h>
// I use glibc error(3) to handle errors
#include <errno.h>
#include <stdlib.h>
#include <fcntl.h>
int main(int argc,char *argv[]){
// no idea if a typo, myFile.txt != logfile.txt
if(!access("myFile.txt", F_OK) == 0) {
error(1, errno, "The file does not exist!");
exit(1);
}
int fd = open("logfile.txt", O_RDONLY | O_NONBLOCK);
if (fd == -1) {
error(1, errno, "Failed opening the file");
}
// move cursor position to the 200th characters from the end
int ret = lseek(fd, -200, SEEK_END);
if (ret == -1) {
error(1, errno, "Failed seeking the file");
}
// we break below
while (1) {
char ch = 0; // holds read char
ssize_t readed = read(fd, &ch, sizeof(ch));
if (readed == 0) {
// end-of-file, break
break;
} else if (readed == -1) {
// error handle
// actually we could handle `readed != 1`
error(1, errno, "Error reading from file");
}
// output the readed character on stdout
// note that `STDOUT_FILENO` as more readable alternative to plain `1`
write(STDOUT_FILENO, &ch, sizeof(ch));
}
close(fd);
return 0;
}

gcc using unlink and readdir, 7 days old files needs to be deleted

Using this code fetched from google.
#include <dirent.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
struct dirent *entry;
DIR *dp;
chdir("/mnt/shared");
dp = opendir(".");
while( (entry = readdir(dp)) != NULL ) {
if ( strcmp(entry->d_name, ".") &&strcmp(entry->d_name, "..") ){
unlink(entry->d_name);
}
}
}`
In this could it be possible to delete files older than 7 days from the current date?
In perl i tried as follows, but wondering this could be achived with your help?
my $now = time();
my $DATEAGE = 60*60*24*7;
for my $file (#file_list) {
my #stats = stat($file);
if ($now-$stats[9] > $DATEAGE) {
print "$file\n";}
Build the full string of the file and use several syscalls(2) (notably stat(2)) ; read Advanced Linux Programming
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
struct dirent *entry;
DIR *dp;
time_t weekago;
time(&weekago);
weekago -= 86400*7;
dp = opendir("/mnt/shared");
if (!dp) { perror("/mnt/shared"); exit(EXIT_FAILURE); };
while( (entry = readdir(dp)) != NULL ) {
if ( strcmp(entry->d_name, ".")
&& strcmp(entry->d_name, "..") ){
char buf[256];
if (snprintf(buf, sizeof(buf),
"/mnt/shared/%s", entry->d_name)
>=sizeof(buf))
{ fprintf(stderr, "too long path %s\n", buf);
exit(EXIT_FAILURE);
};
struct stat st;
if (stat(buf,&st)) {
perror(buf);
exit(EXIT_FAILURE);
};
if ((st.st_mode & S_IFMT) == S_IFREG // a plain file
&& (st.st_mtime < weekago))
{
if (remove(buf)) perror(buf);
}
}
}
My untested code above is imperfect (and not very well indented): it don't handle file paths wider than 255. But you could improve it, e.g. using asprintf(3) to build the path in heap (then you'll need to free it).
Practically speaking, use find(1). If you need to recurse in a file tree in C, use nftw(3)

C shell printing output infinitely without stopping at gets()

I am trying to use the SIGCHLD handler but for some reason it prints of the command I gave infinitely. If I remove the struct act it works fine.
Can anyone take a look at it, I am not able to understand what the problem is.
Thanks in advance!!
/* Simplest dead child cleanup in a SIGCHLD handler. Prevent zombie processes
but dont actually do anything with the information that a child died. */
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
typedef char *string;
/* SIGCHLD handler. */
static void sigchld_hdl (int sig)
{
/* Wait for all dead processes.
* We use a non-blocking call to be sure this signal handler will not
* block if a child was cleaned up in another part of the program. */
while (waitpid(-1, NULL, WNOHANG) > 0) {
}
}
int main (int argc, char *argv[])
{
struct sigaction act;
int i;
int nbytes = 100;
char my_string[nbytes];
string arg_list[5];
char *str;
memset (&act, 0, sizeof(act));
act.sa_handler = sigchld_hdl;
if (sigaction(SIGCHLD, &act, 0)) {
perror ("sigaction");
return 1;
}
while(1){
printf("myshell>> ");
gets(my_string);
str=strtok(my_string," \n");
arg_list[0]=str;
i =1;
while ( (str=strtok (NULL," \n")) != NULL){
arg_list[i]= str;
i++;
}
if (i==1)
arg_list[i]=NULL;
else
arg_list[i+1]=NULL;
pid_t child_pid;
child_pid=fork();
if (child_pid == (pid_t)-1){
printf("ERROR OCCURED");
exit(0);
}
if(child_pid!=0){
printf("this is the parent process id is %d\n", (int) getpid());
printf("the child's process ID is %d\n",(int)child_pid);
}
else{
printf("this is the child process, with id %d\n", (int) getpid());
execvp(arg_list[0],arg_list);
printf("this should not print - ERROR occured");
abort();
}
}
return 0;
}
I haven't run your code, and am merely hypothesizing:
SIGCHLD is arriving and interrupting fgets (I'll just pretend you didn't use gets). fgets returns before actually reading any data, my_string contains the tokenized list that it had on the previous loop, you fork again, enter fgets, which is interrupted before reading any data, and repeat indefinitely.
In other words, check the return value of fgets. If it is NULL and has set errno to EINTR, then call fgets again. (Or set act.sa_flags = SA_RESTART.)

opencv sample code run time error using argv[]

I run this sample cod, and i get run time exception
#include "stdafx.h"
#include <iostream>
using namespace std;
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
using namespace cv;
int _tmain(int argc, char** argv)
{
//IplImage* img = cvLoadImage( "Walk1001.jpg" ,1 );
IplImage* img =cvLoadImage( argv[1] );
if(!img)
cout << "Could not open or find the image" << endl ;
cvNamedWindow( "Example1", 1 );
cvShowImage( "Example1", img );
cvWaitKey(0);
cvReleaseImage( &img );
cvDestroyWindow( "Example1" );
return 0;
}
when i use IplImage* img = cvLoadImage( "Walk1001.jpg" ,1 ); instead of this IplImage* img =cvLoadImage( argv[1] ); program runs fine. but otherwise i got error.
What is to do with argv. i have came across many programs in which image is loaded through some argv[] syntex! how to use this array (argv[]) or what else?
to use the argv array, you've got to supply arguments to your program (from the cmdline, or similar)
prog.exe Walk1001.jpg 19
now argv holds 3 elements, [ "prog.exe", "Walk1001.jpg", "19" ], and argc==3
in your program , do:
char * imgPath="Walk1001.jpg"; // having defaults is a good idea
if ( argc > 1 ) // CHECK if there's actual arguments !
{
imgPath = argv[1]; // argv[0] holds the program-name
}
int number = 24;
if ( argc > 2 ) // CHECK again, if there's enough arguments
{
number = atoi(argv[2]); // you get the picture..
}
sidenote: you seem to be a beginner (nothing wrong with that!), the opencv api has changed over the years, please don't use IplImage* and cv*Functions(the 1.0 api),
use cv::Mat and functions from cv:: namespace.
using namespace cv;
int main(int argc, char** argv)
{
char * imgPath="Walk1001.jpg";
if ( argc > 1 )
{
imgPath = argv[1];
}
Mat img = imread( imgPath );
if ( img.empty() )
{
cout << "Could not open or find the image" << endl ;
return 1;
}
namedWindow( "Example1", 1 );
imshow( "Example1", img );
waitKey(0);
// no, you don't have to release Mat !
return 0;
}
I am getting run time exception. the error is line 2482 unknown function in array.cpp? I think i get this message from imshow after debugging. I'm using Mat img=imread("walk100.jpg"); but the img.total() returning NULL. why imread is returning NULL. cvload is working perfectly.
I got this solved, on the web i came to know about ***d.dll. while adding dll files, I omitted the d, that is for release mode not for debug mode. So I just place "d", like opencv_core244d.dll instead of opencv_core244.dll
thanks all for your contribution

Saving video as series of images opencv

This question is in continuation of error-in-opencv-code-for-motion-detection. The editted code works without any errors but the output video is not created,it is of zero bytes!What is wrong in this?Also,the bounding box created for motion detection never really captures the motion that is, it does not do what it originally claimed to do.Am I misunderstanding something about the objective of thie code?So, here are my questions:
How to rectify the creation and save the video?
What needs to be modified to detect motion and track it?
How to convert the video to a series of numbered jpg images from each frame and vice-versa.
Here is the code which you can work with to frame a video as a set of images.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "cv.h"
#include <highgui.h>
#include "cxcore.h"
int main( int argc, char** argv )
{
CvCapture *capture = cvCaptureFromAVI("E:\\Myvideo.avi");
if(!capture)
{
printf("!!! cvCaptureFromAVI failed (file not found?)\n");
return -1;
}
int fps = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FPS);
printf("* FPS: %d\n", fps);
IplImage* frame = NULL;
int frame_number = 0;
char key = 0;
while (key != 'q')
{
// get frame
frame = cvQueryFrame(capture);
if (!frame)
{
printf("!!! cvQueryFrame failed: no frame\n");
break;
}
// quit when user press 'q'
key = cvWaitKey(1000 / fps);
}
// free resources
cvReleaseCapture(&capture);
return 0;
}

Resources