Beispiel #1
0
/// Helper for builtin_disown.
static int disown_job(const wchar_t *cmd, parser_t &parser, io_streams_t &streams, job_t *j) {
    if (j == 0) {
        streams.err.append_format(_(L"%ls: Unknown job '%ls'\n"), L"bg");
        builtin_print_error_trailer(parser, streams.err, cmd);
        return STATUS_INVALID_ARGS;
    }

    // Stopped disowned jobs must be manually signaled; explain how to do so.
    if (j->is_stopped()) {
        killpg(j->pgid, SIGCONT);
        const wchar_t *fmt =
            _(L"%ls: job %d ('%ls') was stopped and has been signalled to continue.\n");
        streams.err.append_format(fmt, cmd, j->job_id, j->command_wcstr());
    }

    for (auto itr = jobs().begin(); itr != jobs().end(); ++itr) {
        auto job = itr->get();
        if (job == j) {
            pid_t pgid = j->pgid;
            add_disowned_pgid(pgid);
            jobs().erase(itr);
            return STATUS_CMD_OK;
        }
    }

    return STATUS_CMD_ERROR;
}
Beispiel #2
0
// JobSubQueue:QueueJobs
//------------------------------------------------------------------------------
void JobSubQueue::QueueJobs( Array< Node * > & nodes )
{
    // Create wrapper Jobs around Nodes
    Array< Job * > jobs( nodes.GetSize() );
    for ( Node * node : nodes )
    {
    	Job * job = FNEW( Job( node ) );
        jobs.Append( job );
    }

    // Sort Jobs by cost
	JobCostSorter sorter;
	jobs.Sort( sorter );

	// lock to add job
	MutexHolder mh( m_Mutex );
    const bool wasEmpty = m_Jobs.IsEmpty();

	m_Jobs.Append( jobs );
    m_Count += (uint32_t)jobs.GetSize();

    if ( wasEmpty )
    {
        return; // skip re-sorting
    }

    // sort merged lists
	m_Jobs.Sort( sorter );
}
Beispiel #3
0
int main(void)
{
	int sd, newsd;
	struct sockaddr_in myend, hisend;
	socklen_t hislen;
	int ret;
	pid_t pid;

	sd = socket(AF_INET, SOCK_STREAM, 0);
	if (sd == -1) {
		perror("socket()");
		goto socket_err;
	}

	myend.sin_family = AF_INET;
	myend.sin_port = 8899;	/* fixme */
	inet_pton(AF_INET, "172.16.30.83", &myend.sin_addr);
	ret = bind(sd, (struct sockaddr *)&myend, sizeof(myend));
	if (ret == -1) {
		perror("bind()");
		goto bind_err;
	}

	listen(sd, 20);

	hislen = sizeof(hisend); /* warning: must init */
	while (1) {
		newsd = accept(sd, (struct sockaddr *)&hisend, &hislen);
		if (newsd == -1) {
			perror("accept()");
			break;
		}

		pid = fork();
		if (pid == -1) {
			perror("fork()");
			close(newsd);
			continue;
		}
		if (pid == 0) {
			jobs(newsd);
			close(newsd);
			close(sd);
			exit(0);
		}

		close(newsd);
	}

	printf("\033[31mbreak\033[0m\n");
	close(sd);

	return 0;

read_newsd_err:
bind_err:
	close(sd);
socket_err:
	return 1;
}
Beispiel #4
0
int Steriss::exec () {
  try {
    std::list<std::string> valid_stems;
    valid_stems.push_back(".tiff");
    valid_stems.push_back(".tif");
    valid_stems.push_back(".bmp");
    valid_stems.push_back(".pgm");
    IO input_images( valid_stems );
    JobSplitter jobs( input_images );

    while( jobs.hasNext() ) {
      // read images
      _current_data = jobs.nextJob();
      sINFO(">> Running job %i of %i", %jobs.currentJob() %jobs.jobCt());

      // do the processing
      preprocess_data ();
      transfer_data ();
      process_data ();

      // write images
      input_images.writeImages( _current_data, jobs.currentStartIndex(), jobs.currentEndIndex() );

      // make sure to release the memory for the next turn
      _current_data.reset();
    }

    sINFO("All done. Now it's up to you - I'll have a break...");
    return EXIT_SUCCESS;
  } catch(std::exception& e) {
    return EXIT_FAILURE;
  }
}
Beispiel #5
0
/// It should search the job list for something matching the given proc.
static bool find_job_by_name(const wchar_t *proc, std::vector<job_id_t> &ids) {
    bool found = false;

    for (const auto &j : jobs()) {
        if (j->command_is_empty()) continue;

        if (match_pid(j->command(), proc)) {
            if (!contains(ids, j->job_id)) {
                // If pids doesn't already have the pgid, add it.
                ids.push_back(j->job_id);
            }
            found = true;
        }

        // Check if the specified pid is a child process of the job.
        for (const process_ptr_t &p : j->processes) {
            if (p->actual_cmd.empty()) continue;

            if (match_pid(p->actual_cmd, proc)) {
                if (!contains(ids, j->job_id)) {
                    // If pids doesn't already have the pgid, add it.
                    ids.push_back(j->job_id);
                }
                found = true;
            }
        }
    }

    return found;
}
Beispiel #6
0
int main(void)
{
	pid_t pid;
	int i;
	struct sigaction act;

	act.sa_handler = SIG_IGN;
	sigemptyset(&act.sa_mask);
	act.sa_flags = SA_NOCLDWAIT;
	sigaction(SIGCHLD, &act, NULL);

	for (i = 0; i < 200; i++) {
		pid = fork();
		/* if error */
		if (pid == 0) {
			jobs();
			return 0;
		}
	}

	while (1) {
		pause();
	}

	return 1;
}
job_t *parser_t::job_get(job_id_t id) {
    job_iterator_t jobs(my_job_list);
    job_t *job;
    while ((job = jobs.next())) {
        if (id <= 0 || job->job_id == id) return job;
    }
    return NULL;
}
Beispiel #8
0
void test2(int nr_threads, int nr_jobs) {
    {
        jobqueue jobs(nr_threads);

        for (int ii=0 ; ii<nr_jobs*100 ; ++ii) {
            jobs.add(boost::bind<int>(&calculatefib, 30));
        }
    }
}
Beispiel #9
0
static bool all_jobs_finished() {
    for (const auto &j : jobs()) {
        // If any job is not completed, return false.
        // If there are stopped jobs, they are ignored.
        if (j->is_constructed() && !j->is_completed() && !j->is_stopped()) {
            return false;
        }
    }
    return true;
}
Beispiel #10
0
static int wait_for_backgrounds(bool any_flag) {
    size_t jobs_len = jobs().size();

    while ((!any_flag && !all_jobs_finished()) || (any_flag && !any_jobs_finished(jobs_len))) {
        if (reader_test_interrupted()) {
            return 128 + SIGINT;
        }
        proc_wait_any();
    }
    return 0;
}
    void timeout()
    {
        lemon::timer_t timer;

        send(_group,mutable_buffer());

        time_duration duration = timer.duration();

        std::cout << "multicast send(" << counter << ") -- success("

                  << duration / 10000000 << "."

                  << std::setw(6) << std::setfill('0') <<(duration % 10000000) / 10

                  << " s)" << std::endl;

        std::cout << "group job counter(" << jobs(runQ()) << ")" << std::endl;

        if(jobs(runQ()) == 1)  exit();

    }
Beispiel #12
0
static bool any_jobs_finished(size_t jobs_len) {
    bool no_jobs_running = true;

    // If any job is removed from list, return true.
    if (jobs_len != jobs().size()) {
        return true;
    }
    for (const auto &j : jobs()) {
        // If any job is completed, return true.
        if (j->is_constructed() && (j->is_completed() || j->is_stopped())) {
            return true;
        }
        // Check for jobs running exist or not.
        if (j->is_constructed() && !j->is_stopped()) {
            no_jobs_running = false;
        }
    }
    if (no_jobs_running) {
        return true;
    }
    return false;
}
Beispiel #13
0
//==============================================================================
GlProgramPipelineHandle Renderer::createDrawQuadProgramPipeline(
	GlProgramHandle frag)
{
	GlDevice& gl = GlDeviceSingleton::get();
	GlCommandBufferHandle jobs(&gl);

	Array<GlProgramHandle, 2> progs = {{m_drawQuadVert->getGlProgram(), frag}};

	GlProgramPipelineHandle ppline(jobs, &progs[0], &progs[0] + 2);
	jobs.finish();

	return ppline;
}
Beispiel #14
0
/**
 * Quash entry point
 *
 * @param argc argument count from the command line
 * @param argv argument vector from the command line
 * @return program exit status
 */
int main(int argc, char** argv) { 
    command_t cmd; //< Command holder argument
      
    start();
    struct sigaction NULL_sa;
    struct sigaction sa;
    sigset_t mask_set;
    sigfillset(&mask_set);
    sigdelset(&mask_set,SIGINT);
    sigdelset(&mask_set,SIGTSTP);
    sa.sa_handler = catchChild;
    sigprocmask(SIG_SETMASK, &mask_set, NULL);
    //TODO: this is involved withe the error 10 problem. Removing it remedies the issue for now but breaks other things.
    sigaction(SIGCHLD, &sa,NULL);//child termination calls catchChild;

    setenv( "WKDIR", getenv("HOME"), 1 );

    puts("hOi! Welcome to Quash!");

    // Main execution loop
    while (is_running()) 
    {
        // NOTE: I would not recommend keeping anything inside the body of
        // this while loop. It is just an example.

        // The commands should be parsed, then executed.
        if( !get_command(&cmd, stdin) );
        else if (!strcmp(cmd.cmdstr, "q")||!strcmp(cmd.cmdstr, "exit")||!strcmp(cmd.cmdstr, "quit"))
            terminate(); // Exit Quash
        else if(!strcmp(cmd.execArgs[0], "set"))
            set(cmd);//set environment variables
        else if(!strcmp(cmd.execArgs[0], "echo"))
            echo(cmd);//echos environment variables
        else if(!strcmp(cmd.execArgs[0], "pwd"))
            pwd(cmd);//prints current working directory
        else if(!strcmp(cmd.execArgs[0], "cd"))
            cd(cmd);//changes the working directory
        else if(!strcmp(cmd.execArgs[0], "jobs"))
            jobs();//prints out a list of currently running jobs
        else if(!strcmp(cmd.execArgs[0], "kill"))
            killChild(cmd);//kills specified job
        else if (!strcmp(cmd.execArgs[0], "wait"))
            sleep(atoi(cmd.execArgs[1]));
        else if (strchr(cmd.cmdstr,'|')!= NULL)
            exec_pipes(cmd);//executes piped commands
        else 
            exec_cmd(cmd);//executes normal commands
    }

    return EXIT_SUCCESS;
}
Beispiel #15
0
/// Return the job id to which the process with pid belongs.
/// If a specified process has already finished but the job hasn't, parser_t::job_get_from_pid()
/// doesn't work properly, so use this function in wait command.
static job_id_t get_job_id_from_pid(pid_t pid) {
    for (const auto &j : jobs()) {
        if (j->pgid == pid) {
            return j->job_id;
        }
        // Check if the specified pid is a child process of the job.
        for (const process_ptr_t &p : j->processes) {
            if (p->pid == pid) {
                return j->job_id;
            }
        }
    }
    return 0;
}
    void timeout()
    {
        std::cout << "taxi counter :" << jobs(runQ()) << std::endl;

        if(jobs(runQ()) == 1) {
            exit();
            return;
        }

        std::vector<job_id>::const_iterator iter,end = _taxis.end();

        for(iter = _taxis.begin(); iter != end; ++ iter)
        {
            try
            {
                send(*iter,mutable_buffer());
            }
            catch(const error_info & e)
            {
                if(!LEMON_ERRORINOF_EQ(e.Error,LEMON_RUNQ_INVALID_JOB_ID)) throw e;
            }

        }
    }
Beispiel #17
0
//==============================================================================
void Hdr::initFb(GlFramebufferHandle& fb, GlTextureHandle& rt)
{
	GlDevice& gl = getGlDevice();

	m_r->createRenderTarget(m_width, m_height, GL_RGB8, GL_RGB, 
		GL_UNSIGNED_BYTE, 1, rt);

	// Set to bilinear because the blurring techniques take advantage of that
	GlCommandBufferHandle jobs(&gl);
	rt.setFilter(jobs, GlTextureHandle::Filter::LINEAR);

	// Create FB
	fb = GlFramebufferHandle(jobs, {{rt, GL_COLOR_ATTACHMENT0}});
	jobs.finish();
}
Beispiel #18
0
//==============================================================================
void Pps::initInternal(const ConfigSet& initializer)
{
	m_enabled = initializer.get("pps.enabled");
	if(!m_enabled)
	{
		return;
	}

	ANKI_ASSERT("Initializing PPS");

	m_ssao.init(initializer);
	m_hdr.init(initializer);
	m_lf.init(initializer);
	m_sslr.init(initializer);

	// FBO
	GlDevice& gl = GlDeviceSingleton::get();
	GlCommandBufferHandle jobs(&gl);

	m_r->createRenderTarget(m_r->getWidth(), m_r->getHeight(), GL_RGB8, GL_RGB,
		GL_UNSIGNED_BYTE, 1, m_rt);

	m_fb = GlFramebufferHandle(jobs, {{m_rt, GL_COLOR_ATTACHMENT0}});

	// SProg
	std::stringstream pps;

	pps << "#define SSAO_ENABLED " << (U)m_ssao.getEnabled() << "\n"
		<< "#define HDR_ENABLED " << (U)m_hdr.getEnabled() << "\n"
		<< "#define SHARPEN_ENABLED " << (U)initializer.get("pps.sharpen") 
			<< "\n"
		<< "#define GAMMA_CORRECTION_ENABLED " 
			<< (U)initializer.get("pps.gammaCorrection") << "\n"
		<< "#define FBO_WIDTH " << (U)m_r->getWidth() << "\n"
		<< "#define FBO_HEIGHT " << (U)m_r->getHeight() << "\n";

	m_frag.load(ProgramResource::createSrcCodeToCache(
		"shaders/Pps.frag.glsl", pps.str().c_str(), "r_").c_str());

	m_ppline = m_r->createDrawQuadProgramPipeline(m_frag->getGlProgram());

	jobs.finish();
}
Beispiel #19
0
//==============================================================================
RenderableDrawer::RenderableDrawer(Renderer* r)
	: m_r(r)
{
	// Create the uniform buffer
	GlDevice& gl = GlDeviceSingleton::get();
	GlCommandBufferHandle jobs(&gl);
	m_uniformBuff = GlBufferHandle(jobs, GL_UNIFORM_BUFFER, 
		MAX_UNIFORM_BUFFER_SIZE,
		GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT);
	jobs.flush();

	m_uniformPtr = (U8*)m_uniformBuff.getPersistentMappingAddress();
	ANKI_ASSERT(m_uniformPtr != nullptr);
	ANKI_ASSERT(isAligned(gl.getBufferOffsetAlignment(
		m_uniformBuff.getTarget()), m_uniformPtr));

	// Set some other values
	m_uniformsUsedSize = 0;
	m_uniformsUsedSizeFrame = 0;
}
Beispiel #20
0
//==============================================================================
void Renderer::createRenderTarget(U32 w, U32 h, GLenum internalFormat, 
	GLenum format, GLenum type, U32 samples, GlTextureHandle& rt)
{
	// Not very important but keep the resulution of render targets aligned to
	// 16
	if(0)
	{
		ANKI_ASSERT(isAligned(16, w));
		ANKI_ASSERT(isAligned(16, h));
	}

	GlTextureHandle::Initializer init;

	init.m_width = w;
	init.m_height = h;
	init.m_depth = 0;
#if ANKI_GL == ANKI_GL_DESKTOP
	init.m_target = (samples == 1) ? GL_TEXTURE_2D : GL_TEXTURE_2D_MULTISAMPLE;
#else
	ANKI_ASSERT(samples == 1);
	init.m_target = GL_TEXTURE_2D;
#endif
	init.m_internalFormat = internalFormat;
	init.m_format = format;
	init.m_type = type;
	init.m_mipmapsCount = 1;
	init.m_filterType = GlTextureHandle::Filter::NEAREST;
	init.m_repeat = false;
	init.m_anisotropyLevel = 0;
	init.m_genMipmaps = false;
	init.m_samples = samples;

	GlDevice& gl = GlDeviceSingleton::get();
	GlCommandBufferHandle jobs(&gl);
	rt = GlTextureHandle(jobs, init);
	jobs.finish();
}
Beispiel #21
0
//==============================================================================
void Renderer::init(const ConfigSet& initializer)
{
	// Set from the initializer
	m_width = initializer.get("width");
	m_height = initializer.get("height");
	m_lodDistance = initializer.get("lodDistance");
	m_framesNum = 0;
	m_samples = initializer.get("samples");
	m_isOffscreen = initializer.get("offscreen");
	m_renderingQuality = initializer.get("renderingQuality");
	m_tilesCount.x() = initializer.get("tilesXCount");
	m_tilesCount.y() = initializer.get("tilesYCount");

	m_tessellation = initializer.get("tessellation");

	// A few sanity checks
	if(m_samples != 1 && m_samples != 4 && m_samples != 8 && m_samples != 16
		&& m_samples != 32)
	{
		throw ANKI_EXCEPTION("Incorrect samples");
	}

	if(m_width < 10 || m_height < 10)
	{
		throw ANKI_EXCEPTION("Incorrect sizes");
	}

	// quad setup
	static const F32 quadVertCoords[][2] = {{1.0, 1.0}, {-1.0, 1.0}, 
		{1.0, -1.0}, {-1.0, -1.0}};

	GlDevice& gl = GlDeviceSingleton::get();
	GlCommandBufferHandle jobs(&gl);

	GlClientBufferHandle tmpBuff = GlClientBufferHandle(jobs, 
		sizeof(quadVertCoords), (void*)&quadVertCoords[0][0]);

	m_quadPositionsBuff = GlBufferHandle(jobs, GL_ARRAY_BUFFER, 
		tmpBuff, 0);

	m_drawQuadVert.load("shaders/Quad.vert.glsl");

	// Init the stages. Careful with the order!!!!!!!!!!
	m_tiler.init(this);

	m_ms.init(initializer);;
	m_is.init(initializer);
	m_bs.init(initializer);
	m_pps.init(initializer);
	m_dbg.init(initializer);

	// Init the shaderPostProcessorString
	std::stringstream ss;
	ss << "#define RENDERING_WIDTH " << m_width << "\n"
		<< "#define RENDERING_HEIGHT " << m_height << "\n";

	m_shaderPostProcessorString = ss.str();

	// Default FB
	m_defaultFb = GlFramebufferHandle(jobs, {});

	jobs.finish();
}
Beispiel #22
0
int run_internal(int term, char* cmd_line)
{
	char cmd[MAX_COMMAND_LEN];
	char params[MAX_COMMAND_LEN];
	int index;

	memset(cmd, '\0', MAX_COMMAND_LEN);
	memset(params, '\0', MAX_COMMAND_LEN);

	if(!strword(1, cmd_line, len(cmd_line)+1, cmd, MAX_COMMAND_LEN)) 
	{
		return 0;
	}

	index = first_index_of(cmd_line, ' ', len(cmd));

	if(index != -1)
		substr(cmd_line, index, -1, params);
	else
		params[0] = '\0';

	trim(params);

	argc[term] = get_param_count(params);
	if(argc[term] > 0)
	{
		args[term] = (char**)malloc(argc[term] * sizeof(char*));
		get_parameters(params, argc[term], args[term]);
	}
	else
	{
		args[term] = NULL;
	}

	if(streq(cmd, "cd"))
	{
		if(streq(params, ""))
  		{
			term_color_print(term, "Wrong parameters.\n\n", 7);
			term_color_print(term, "Usage: cd path.\n\n", 7);
		}
		else
		{
			change_dir(term, params);
		}
		free_params(term);

		return TRUE;
	}
	else if(streq(cmd, "set"))
	{
		// allows setting, listing or removing global and console variables
		set_cmd(term, args[term], argc[term]);
		free_params(term);
		return TRUE;
	}
	else if(streq(cmd, "jobs"))
	{
		// allows setting, listing or removing global and console variables
		jobs(term, args[term], argc[term]);
		free_params(term);
		return TRUE;
	}
	else if(streq(cmd, "kill"))
	{
		// allows setting, listing or removing global and console variables
		kill(term, args[term], argc[term]);
		free_params(term);
		return TRUE;
	}
	else if(streq(cmd, "clear"))
	{
		term_clean(term);
		free_params(term);
		return TRUE;
	}
	else if(streq(cmd, "initofs")) // this command should dissapear in a future
	{
		init_ofs(term, args[term], argc[term]);
		free_params(term);
		return TRUE;
	}
	else if(streq(cmd, "mkdir")) 
	{
		mkdir_cmd(term, args[term], argc[term]);
		free_params(term);
		return TRUE;
	}
	else if(streq(cmd, "rm")) 
	{
		rm_cmd(term, args[term], argc[term]);
		free_params(term);
		return TRUE;
	}
	else if(streq(cmd, "ls")) 
	{
		ls(term, args[term], argc[term]);
		free_params(term);
		return TRUE;
	}
	else if(streq(cmd, "mkdevice")) 
	{
		mkdevice_cmd(term, args[term], argc[term]);
		free_params(term);
		return TRUE;
	}
	else if(streq(cmd, "ofsformat")) 
	{
		ofsformat(term, args[term], argc[term]);
		free_params(term);
		return TRUE;
	}
	/*else if(streq(cmd, "cat")) 
	{
		cat(term, args[term], argc[term]);
		free_params(term);
		return TRUE;
	}*/
	else if(streq(cmd, "write"))
	{
		write(term, args[term], argc[term]);
		free_params(term);
		return TRUE;
	}
	else if(streq(cmd, "mount"))
	{
		mount_cmd(term, args[term], argc[term]);
		free_params(term);
		return TRUE;
	}
	else if(streq(cmd, "umount"))
	{
		umount_cmd(term, args[term], argc[term]);
		free_params(term);
		return TRUE;
	}
	else if(streq(cmd, "chattr"))
	{
		chattr_cmd(term, args[term], argc[term]);
		free_params(term);
		return TRUE;
	}
	else if(streq(cmd, "ln"))
	{
		mklink_cmd(term, args[term], argc[term]);
		free_params(term);
		return TRUE;
	}
	else if(streq(cmd, "contest"))
	{
		contest(term, args[term], argc[term]);
		free_params(term);
		return TRUE;
	}
    else if(streq(cmd, "atactst"))
	{
		atactst(term, args[term], argc[term]);
		free_params(term);
		return TRUE;
	}
    else if(streq(cmd, "dyntst"))
	{
		dyntst(term, args[term], argc[term]);
		free_params(term);
		return TRUE;
	}
	free_params(term);
	return FALSE;
}
Beispiel #23
0
/// Builtin for removing jobs from the job list.
int builtin_disown(parser_t &parser, io_streams_t &streams, wchar_t **argv) {
    const wchar_t *cmd = argv[0];
    int argc = builtin_count_args(argv);
    help_only_cmd_opts_t opts;

    int optind;
    int retval = parse_help_only_cmd_opts(opts, &optind, argc, argv, parser, streams);
    if (retval != STATUS_CMD_OK) return retval;

    if (opts.print_help) {
        builtin_print_help(parser, streams, cmd, streams.out);
        return STATUS_CMD_OK;
    }

    if (argv[1] == 0) {
        // Select last constructed job (ie first job in the job queue) that is possible to disown.
        // Stopped jobs can be disowned (they will be continued).
        // Foreground jobs can be disowned.
        // Even jobs that aren't under job control can be disowned!
        job_t *job = nullptr;
        for (const auto &j : jobs()) {
            if (j->is_constructed() && (!j->is_completed())) {
                job = j.get();
                break;
            }
        }

        if (job) {
            retval = disown_job(cmd, parser, streams, job);
        } else {
            streams.err.append_format(_(L"%ls: There are no suitable jobs\n"), cmd);
            retval = STATUS_CMD_ERROR;
        }
    } else {
        std::set<job_t *> jobs;

        // If one argument is not a valid pid (i.e. integer >= 0), fail without disowning anything,
        // but still print errors for all of them.
        // Non-existent jobs aren't an error, but information about them is useful.
        // Multiple PIDs may refer to the same job; include the job only once by using a set.
        for (int i = 1; argv[i]; i++) {
            int pid = fish_wcstoi(argv[i]);
            if (errno || pid < 0) {
                streams.err.append_format(_(L"%ls: '%ls' is not a valid job specifier\n"), cmd,
                                          argv[i]);
                retval = STATUS_INVALID_ARGS;
            } else {
                if (job_t *j = parser.job_get_from_pid(pid)) {
                    jobs.insert(j);
                } else {
                    streams.err.append_format(_(L"%ls: Could not find job '%d'\n"), cmd, pid);
                }
            }
        }
        if (retval != STATUS_CMD_OK) {
            return retval;
        }

        // Disown all target jobs
        for (const auto &j : jobs) {
            retval |= disown_job(cmd, parser, streams, j);
        }
    }

    return retval;
}
Beispiel #24
0
/**
 * Quash entry point
 *
 * @param argc argument count from the command line
 * @param argv argument vector from the command line
 * @return program exit status
 */
int main(int argc, char** argv) { 
  command_t cmd; //< Command holder argument
  
  char tmpCmd[1024];
  memset(tmpCmd, 0, 1024);

  memset(backprocess,0,sizeof(command_t)*MAX_BACKGROUND_TASKS);

  struct sigaction sa;
  sigset_t mask_set;  /* used to set a signal masking set. */
  /* setup mask_set */
  sigemptyset(&mask_set);
  sigfillset(&mask_set);//prevent other interupts from interupting intrupts
  sa.sa_mask = mask_set;
  sa.sa_handler = catch_sigchld;
  sigaction(SIGCHLD,&sa,NULL);

  start();
  
  puts("Welcome to Quash!");
  printf("$PATH is: %s\n", pPath);
  printf("$HOME is: %s\n", hHome);
  puts("Type \"exit\" to quit");

  // Main execution loop
  while (is_running() && get_command(&cmd, stdin)) {
    //Copy the command string to a temporary variable.
    memset(tmpCmd, 0, 1024);
    strcpy(tmpCmd, cmd.cmdstr);

    //Split tmpCmd to get the command 
    char *tok;
    tok = strtok(tmpCmd, " ");
    
    //If not receiving any command from user, skip iteration to prevent segmentation fault.
    if ((strlen(tmpCmd) == 0)||(tok == NULL)){
      continue;
    }
    if(cmd.cmdstr[cmd.cmdlen-1] == '&'){//is a background process
      cmd.cmdstr[cmd.cmdlen-1] = '\0';
      if(cmd.cmdstr[cmd.cmdlen-2] == ' '){
        cmd.cmdstr[cmd.cmdlen-2] = '\0';
      }
      cmd.background = true;

    }else{
      cmd.background = false;
    }

    // The commands should be parsed, then executed.
    if ((!strcmp(tmpCmd, "exit")) ||(!strcmp(tmpCmd, "quit")))//if the command is "exit"
    {
      terminate(); // Exit Quash
    }
    else if(strcmp(tok, "echo") == 0){
      echo(strtok(NULL, ""));
    }
    else if(strcmp(tok, "cd") == 0){
      cd(strtok(NULL, ""));
    }
    else if(strcmp(tok, "pwd") == 0){
      pwd();
    }
    else if(strcmp(tok, "set") == 0){
      set(strtok(NULL, ""));
    }
    else if(strcmp(tok, "jobs") == 0){
      jobs();
    }
    else if(strcmp(tok, "kill") == 0){
      char *sigNum = strtok(NULL, " ");
      char *jobID = strtok(NULL, " ");
      
      if (sigNum == NULL || jobID == NULL){
          printf("Error. Invalid number of arguments.\n");
          continue;
      }
      else{
          int intSigNum = atoi(sigNum);
          int intjobID = atoi(jobID);
   
          killBack(intSigNum, intjobID);
      }
    }
    else 
    {
      memset(tmpCmd, 0, 1024);
      strcpy(tmpCmd, cmd.cmdstr);
      FILE *infileptr = NULL;
      FILE *outfileptr = NULL;
      int infiledsc = -1;
      int outfiledsc = -1;
      if(strchr(tmpCmd,'<') != NULL){
        char *tmp = strchr(tmpCmd,'<')+1;
        if(strncmp(tmp," ",1)==0)//if space, move ahead by one.
          tmp++;
        strtok(tmp, " ");//find next space or end of string. and put \0
        infileptr = fopen(tmp,"r");
        if(infileptr != NULL){
          infiledsc = fileno(infileptr);
        }else{
          perror ("The following error occurred");
          continue;
        }
      }
      strcpy(tmpCmd, cmd.cmdstr);
      if(strchr(tmpCmd,'>') != NULL){
        char *tmp = strchr(tmpCmd,'>')+1;
        if(strncmp(tmp," ",1)==0)//if space, move ahead by one.
          tmp++;
        strtok(tmp, " ");//find next space or end of string. and put \0

        outfileptr = fopen(tmp,"w+");
        outfiledsc = fileno(outfileptr);
      }
      strtok(cmd.cmdstr, "<>");//add \0 to begining of <> segment to designate end of string.
      cmd.cmdlen = strlen(cmd.cmdstr);
      
      genCmd(&cmd,infiledsc,outfiledsc);
      
      if(infileptr != NULL)
        fclose(infileptr);
      if(outfileptr != NULL)
        fclose(outfileptr);
    }
  }
  return EXIT_SUCCESS;
}
//==============================================================================
void TextureResource::loadInternal(const CString& filename, 
	ResourceInitializer& rinit)
{
	GlDevice& gl = rinit.m_resources._getGlDevice();
	GlCommandBufferHandle jobs(&gl); // Always first to avoid assertions (
	                                 // because of the check of the allocator)

	GlTextureHandle::Initializer init;
	U layers = 0;
	Bool driverShouldGenMipmaps = false;

	// Load image
	Image* imgPtr = rinit.m_alloc.newInstance<Image>(rinit.m_alloc);
	Image& img = *imgPtr;
	img.load(filename, rinit.m_resources.getMaxTextureSize());
	
	// width + height
	init.m_width = img.getSurface(0, 0).m_width;
	init.m_height = img.getSurface(0, 0).m_height;
	
	// depth
	if(img.getTextureType() == Image::TextureType::_2D_ARRAY 
		|| img.getTextureType() == Image::TextureType::_3D)
	{
		init.m_depth = img.getDepth();
	}
	else
	{
		init.m_depth = 0;
	}

	// target
	switch(img.getTextureType())
	{
	case Image::TextureType::_2D:
		init.m_target = GL_TEXTURE_2D;
		layers = 1;
		break;
	case Image::TextureType::CUBE:
		init.m_target = GL_TEXTURE_CUBE_MAP;
		layers = 6;
		break;
	case Image::TextureType::_2D_ARRAY:
		init.m_target = GL_TEXTURE_2D_ARRAY;
		layers = init.m_depth;
		break;
	case Image::TextureType::_3D:
		init.m_target = GL_TEXTURE_3D;
		layers = init.m_depth;
	default:
		ANKI_ASSERT(0);
	}

	// Internal format
	if(img.getColorFormat() == Image::ColorFormat::RGB8)
	{
		switch(img.getCompression())
		{
		case Image::DataCompression::RAW:
#if DRIVER_CAN_COMPRESS
			init.m_internalFormat = GL_COMPRESSED_RGB;
#else
			init.m_internalFormat = GL_RGB;
#endif
			driverShouldGenMipmaps = true;
			break;
#if ANKI_GL == ANKI_GL_DESKTOP
		case Image::DataCompression::S3TC:
			init.m_internalFormat = GL_COMPRESSED_RGB_S3TC_DXT1_EXT;
			break;
#else
		case Image::DataCompression::ETC:
			init.m_internalFormat = GL_COMPRESSED_RGB8_ETC2;
			break;
#endif
		default:
			ANKI_ASSERT(0);
		}
	}
	else if(img.getColorFormat() == Image::ColorFormat::RGBA8)
	{
		switch(img.getCompression())
		{
		case Image::DataCompression::RAW:
#if DRIVER_CAN_COMPRESS
			init.m_internalFormat = GL_COMPRESSED_RGBA;
#else
			init.m_internalFormat = GL_RGBA;
#endif
			driverShouldGenMipmaps = true;
			break;
#if ANKI_GL == ANKI_GL_DESKTOP
		case Image::DataCompression::S3TC:
			init.m_internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
			break;
#else
		case Image::DataCompression::ETC:
			init.m_internalFormat = GL_COMPRESSED_RGBA8_ETC2_EAC;
			break;
#endif
		default:
			ANKI_ASSERT(0);
		}
	}
	else
	{
		ANKI_ASSERT(0);
	}

	// format
	switch(img.getColorFormat())
	{
	case Image::ColorFormat::RGB8:
		init.m_format = GL_RGB;
		break;
	case Image::ColorFormat::RGBA8:
		init.m_format = GL_RGBA;
		break;
	default:
		ANKI_ASSERT(0);
	}

	// type
	init.m_type = GL_UNSIGNED_BYTE;

	// mipmapsCount
	init.m_mipmapsCount = img.getMipLevelsCount();

	// filteringType
	init.m_filterType = GlTextureHandle::Filter::TRILINEAR;

	// repeat
	init.m_repeat = true;

	// anisotropyLevel
	init.m_anisotropyLevel = rinit.m_resources.getTextureAnisotropy();

	// genMipmaps
	if(init.m_mipmapsCount == 1 || driverShouldGenMipmaps)
	{
		init.m_genMipmaps = true;
	}
	else
	{
		init.m_genMipmaps = false;
	}

	// Now assign the data
	for(U layer = 0; layer < layers; layer++)
	{
		for(U level = 0; level < init.m_mipmapsCount; level++)
		{
			GlClientBufferHandle& buff = init.m_data[level][layer];

			buff = GlClientBufferHandle(
				jobs, 
				img.getSurface(level, layer).m_data.size(), 
				(void*)&img.getSurface(level, layer).m_data[0]);
		}
	}

	// Add the GL job to create the texture
	m_tex = GlTextureHandle(jobs, init);

	// Add cleanup job
	jobs.pushBackUserCommand(deleteImageCallback, imgPtr);

	// Finaly enque the GL job chain
	jobs.flush();
}
    void timeout()
    {
        std::cout << "taxi counter :" << jobs(runQ()) << std::endl;

        if(_proxyCounter == maxTaxis) exit();
    }
int main(int argc, char *argv[])
{

	srand(1);
	cout.precision(10);

	//-------------------- program parameters ---------------------------
	// 10 parameters required
	if(argc != 10)
	{
		cerr << "need 10 parameters" << endl;
		cerr << "santa.x datadir start_file_name BETA cool_speed lon_width lat_width stopping_cond save_file_name N_THREADS" << endl;
		return 0;
	}

	string datadir = string(argv[1]); // data directory

	// read input solution
	trips = load_data(datadir + string(argv[2]));
	for(auto &t:trips) t.update_info();
	cout << "total trips " << trips.size() << endl;
	double ss = totalscore(trips);
	cout << "initial score: " << ss << endl;
	int N = trips.size();

	// initial temperature and cooling rate
	BETA = atof(argv[3]);                  //annealing starting beta = 1/T (temperature)
	double cooling_speed = atof(argv[4]);  //annealing cooling speed

	// local search range limitation
	longitude_difference_threshold = atof(argv[5]);
	latitude_difference_threshold = atof(argv[6]);

	// stopping condition: stop when number of performed moves in the last iteration is less than a given value (stopping_suc)
	int stopping_suc = atoi(argv[7]);
	bool sep = false;

	//--------------------------------------------------------------------

	//initialize the random generator
	for(int i = 0; i < 32; i++) rs[i] = rand();
	
	prob[1] = prob[2] = prob[3] = 1;
	NMB_THREADS = atoi(argv[9]);
	assert(NMB_THREADS <= 16);    //don't use too many cores or else wasted


	double goodresult = min(1.240e13, ss) - 1e7;
	time_t start = time(NULL);
	vector<int> suc(prob.size(), 0);

	// Simulated Annealing procedure
	int nmbIters = 5000000;
	for(int i = 1; i < nmbIters; i++)
	{
		assert(trips.size() < MAXTRIP);          //mtx array size limit
		for(auto &t:trips) t.update_range();
		int Npair = set_working_pairs(trip_pairs, trips, sep, longitude_difference_threshold);

		// do it in parallel
		vector<thread> jobs(NMB_THREADS);
		for(int l = 0; l < NMB_THREADS; l++) jobs[l] = thread(parallel_job, &suc, l);
		for(int l = 0; l < NMB_THREADS; l++) jobs[l].join();

		if(i % 10 == 0)
		{
			for(auto &t:trips){ t.update_info(); }
			//recalculate auxiliary variables to avoid accumulated errors
			//remove empty trips
			int b = trips.size();
			trips.erase(remove_if(trips.begin(),trips.end(), [](Trip &t){return t.size()<=2;}), trips.end());
			int e = trips.size();
			if(b != e) cout << " empty trips removed : " << b - e << endl;

			double cutscore = selfupdateCut(trips, 0);

			time_t now = time(NULL);
			cout << " - Estimated time remaining: " << log(2000/BETA) / log(cooling_speed) * difftime(now,start)/i/3600.0 << " hours" << endl;
		}
		
		if(i % 2 == 0)
		{
			ss = totalscore(trips);
			cout << i << " :";
			for(auto x:suc) cout << x << ' ';
			cout << shift11_count << ' ';
			shift11_count = 0;
			cout << " score: " << ss << endl;
			if(ss < goodresult)
			{
				cout << "save at beta = " << BETA << endl;
				save_result(trips,datadir + to_string(int(ss/1e7))+".csv");
				goodresult = ss - 1e7;
			}

			if(suc[0] < stopping_suc)break;
			for(int k = 0; k < suc.size(); k++) suc[k] = 0;
		}

		BETA *= cooling_speed;

	}


	//end

	time_t end = time(NULL);
	cout << "time: " << difftime(end,start) << " seconds" << endl;

	double ss2 = totalscore(trips,true);
	cout << "check true total score " << ss2 << ' ' << ss2 - ss << endl;
	int count = 0;
	for(auto &trip:trips) if(trip.size() > 3) count++;
	cout << "total trips remained" << count << endl;

	save_result(trips,datadir+string(argv[8]));
	return 0;
}
Beispiel #28
0
void test_collection (void)
{
  std::cerr <<
    "************* COLLECTION: Testing container collections*************\n";

  knowledge::KnowledgeBase knowledge;
  knowledge::ThreadSafeContext & context (knowledge.get_context ());

  unsigned char buffer1[1024];
  unsigned char buffer2[2048];

  std::cerr << "  Creating containers...\n";

  containers::Integer age ("age", knowledge);
  containers::String name ("name", knowledge);
  containers::Double salary ("salary", knowledge);
  containers::NativeDoubleVector gps_location ("location.gps", knowledge, 3);
  containers::NativeIntegerVector years_employed ("employment.years", knowledge);
  containers::Map jobs ("jobs", knowledge);
  containers::BufferVector images ("images", knowledge);
  containers::StringVector movies ("movies.favorite", knowledge);
  containers::IntegerVector years ("years.favorite", knowledge);
  containers::IntegerVector sensors_ready ("sensors_ready", knowledge, 3);
  containers::DoubleVector coolfactor ("coolfactor.by.year", knowledge, 35);

  std::cerr << "  Testing modifieds.size == 2 after container creation... ";

  if (context.get_modifieds ().size () != 2)
  {
    std::cerr << "FAIL\n";
    std::cerr << "    Printing modified elements in context\n\n";
    std::cerr << context.debug_modifieds () << "\n";
  }
  else
  {
    std::cerr << "SUCCESS\n";
  }

  std::cerr << "  Assigning values to containers...\n";

  age = 40;
  name = "Jack Franklin";
  salary = 45000.0;
  gps_location.set (2, 1000.0);
  gps_location.set (0, 72.0);
  gps_location.set (1, 40.0);
  years_employed.set (0, 1998);
  years_employed.push_back (1999);
  years_employed.push_back (2005);
  years_employed.push_back (2007);
  years_employed.push_back (2010);
  years_employed.push_back (2011);
  years_employed.push_back (2012);
  years_employed.push_back (2013);
  years_employed.push_back (2014);
  years_employed.push_back (2015);
  jobs.set ("Albert's", "Courtesy Clerk");
  jobs.set ("Nursery House", "Plant Care Technician");
  jobs.set ("Johnson's", "Landscaping Expert");
  images.push_back (buffer1, sizeof (buffer1));
  images.push_back (buffer2, sizeof (buffer2));
  movies.push_back ("Edge of Tomorrow");
  movies.push_back ("Fight Club");
  movies.push_back ("Seven");
  movies.push_back ("Serenity");
  years.push_back (2000);
  years.push_back (2012);
  coolfactor.set (0, 10.0);
  coolfactor.set (1, 12.0);
  coolfactor.set (2, 10.5);
  coolfactor.set (3, 9);
  coolfactor.set (4, 8);
  coolfactor.set (5, 8.5);
  coolfactor.set (6, 8.5);
  coolfactor.set (7, 8.5);
  coolfactor.set (8, 8);
  coolfactor.set (9, 9);
  coolfactor.set (10, 10);
  coolfactor.set (11, 10);
  coolfactor.set (12, 11);
  coolfactor.set (13, 11);
  coolfactor.set (14, 6);
  coolfactor.set (15, 7);
  coolfactor.set (16, 20);
  coolfactor.set (17, 30);
  coolfactor.set (18, 35);
  coolfactor.set (19, 25);
  coolfactor.set (20, 20);
  coolfactor.set (21, 35);
  coolfactor.set (22, 30);
  coolfactor.set (23, 22);
  coolfactor.set (24, 18);
  coolfactor.set (25, 14);
  coolfactor.set (26, 11);
  coolfactor.set (27, 10);
  coolfactor.set (28, 9);
  coolfactor.set (29, 9);
  coolfactor.set (30, 5);
  coolfactor.set (31, 5);
  coolfactor.set (32, 4);
  coolfactor.set (33, 3);
  coolfactor.set (34, 3);
  sensors_ready.set (0, 1);
  sensors_ready.set (2, 1);

  containers::Collection collection;

  std::cerr << "\n  Adding 10 containers to collection container\n";

  collection.add (age);
  collection.add (name);
  collection.add (salary);
  collection.add (gps_location);
  collection.add (years_employed);
  collection.add (jobs);
  collection.add (images);
  collection.add (movies);
  collection.add (years);
  collection.add (coolfactor);

  std::cerr << "  Testing collection.size == 10 after adding containers... ";

  if (collection.size () != 10)
  {
    std::cerr << "FAIL. Size returned " << collection.size () << "\n";
  }
  else
  {
    std::cerr << "SUCCESS\n";
  }

  std::cerr << "\n  Printing Collection contents\n\n";
  std::cerr << collection.get_debug_info () << "\n";

  std::cerr << "  Printing modified elements in context\n\n";
  std::cerr << context.debug_modifieds () << "\n";

  std::cerr << "  Clearing modified elements in context\n\n";
  knowledge.clear_modifieds ();

  std::cerr << "  Testing modifieds.size == 0 after clearing modified... ";

  if (context.get_modifieds ().size () != 0)
  {
    std::cerr << "FAIL\n";
    std::cerr << "    Printing modified elements in context\n\n";
    std::cerr << context.debug_modifieds () << "\n";
  }
  else
  {
    std::cerr << "SUCCESS\n";
  }

  std::cerr << "  Calling modify on collection\n";
  collection.modify ();

  std::cerr << "  Testing modifieds.size == 55 after modifying containers... ";

  if (context.get_modifieds ().size () != 55)
  {
    std::cerr << "FAIL\n";
  }
  else
  {
    std::cerr << "SUCCESS\n";
  }

  std::cerr << "  Printing modified elements in context\n\n";
  std::cerr << context.debug_modifieds () << "\n";

  std::cerr << "  Clearing modified elements in context\n\n";
  knowledge.clear_modifieds ();

  std::cerr << "  Clearing collection\n\n";
  collection.clear ();

  std::cerr << "  Testing collection.size == 0 after clearing containers... ";

  if (collection.size () != 0)
  {
    std::cerr << "FAIL. Size returned " << collection.size () << "\n";
  }
  else
  {
    std::cerr << "SUCCESS\n";
  }

  std::cerr << "\nAdding 3 containers to collection container\n";

  collection.add (age);
  collection.add (name);
  collection.add (salary);

  std::cerr << "  Testing collection.size == 3 after adding containers... ";

  if (collection.size () != 3)
  {
    std::cerr << "FAIL. Size returned " << collection.size () << "\n";
  }
  else
  {
    std::cerr << "SUCCESS\n";
  }

  std::cerr << "\nPrinting Collection contents\n\n";
  std::cerr << collection.get_debug_info () << "\n";

  std::cerr << "  Calling modify on collection\n";
  collection.modify ();

  std::cerr << "  Testing modifieds.size == 3... ";

  if (context.get_modifieds ().size () != 3)
  {
    std::cerr << "FAIL\n";
  }
  else
  {
    std::cerr << "SUCCESS\n";
  }

  std::cerr << "  Printing modified elements in context\n\n";
  std::cerr << context.debug_modifieds () << "\n";

  std::cerr << "  Clearing modified elements in context\n\n";
  knowledge.clear_modifieds ();


  std::cerr << "  Calling modify_if_true on collection\n";
  collection.modify_if_true (sensors_ready);

  std::cerr << "  Testing modifieds.size == 0... ";

  if (context.get_modifieds ().size () != 0)
  {
    std::cerr << "FAIL\n";
  }
  else
  {
    std::cerr << "SUCCESS\n";
  }

  std::cerr << "  Updating final sensors ready to true\n";
  sensors_ready.set (1, 1);

  std::cerr << "  Calling modify_if_true on collection\n";
  collection.modify_if_true (sensors_ready);

  std::cerr << "  Testing modifieds.size == 4... ";

  if (context.get_modifieds ().size () != 4)
  {
    std::cerr << "FAIL\n";
    std::cerr << "    Printing modified elements in context\n\n";
    std::cerr << context.debug_modifieds () << "\n";
  }
  else
  {
    std::cerr << "SUCCESS\n";
  }

}
Beispiel #29
0
//==============================================================================
void Hdr::initInternal(const ConfigSet& initializer)
{
	m_enabled = initializer.get("pps.hdr.enabled");

	if(!m_enabled)
	{
		return;
	}

	const F32 renderingQuality = initializer.get("pps.hdr.renderingQuality");

	m_width = renderingQuality * (F32)m_r->getWidth();
	alignRoundDown(16, m_width);
	m_height = renderingQuality * (F32)m_r->getHeight();
	alignRoundDown(16, m_height);

	m_exposure = initializer.get("pps.hdr.exposure");
	m_blurringDist = initializer.get("pps.hdr.blurringDist");
	m_blurringIterationsCount = 
		initializer.get("pps.hdr.blurringIterationsCount");

	initFb(m_hblurFb, m_hblurRt);
	initFb(m_vblurFb, m_vblurRt);

	// init shaders
	GlDevice& gl = getGlDevice();
	GlCommandBufferHandle jobs(&gl);

	m_commonBuff = GlBufferHandle(jobs, GL_SHADER_STORAGE_BUFFER, 
		sizeof(Vec4), GL_DYNAMIC_STORAGE_BIT);

	updateDefaultBlock(jobs);

	jobs.flush();

	m_toneFrag.load("shaders/PpsHdr.frag.glsl", &getResourceManager());

	m_tonePpline = 
		m_r->createDrawQuadProgramPipeline(m_toneFrag->getGlProgram());

	const char* SHADER_FILENAME = 
		"shaders/VariableSamplingBlurGeneric.frag.glsl";

	String pps(getAllocator());
	pps.sprintf("#define HPASS\n"
		"#define COL_RGB\n"
		"#define BLURRING_DIST float(%f)\n"
		"#define IMG_DIMENSION %u\n"
		"#define SAMPLES %u\n",
		m_blurringDist, m_height, 
		static_cast<U>(initializer.get("pps.hdr.samples")));

	m_hblurFrag.load(ProgramResource::createSourceToCache(
		SHADER_FILENAME, pps.toCString(), "r_", 
		getResourceManager()).toCString(),
		&getResourceManager());

	m_hblurPpline = 
		m_r->createDrawQuadProgramPipeline(m_hblurFrag->getGlProgram());

	pps.sprintf("#define VPASS\n"
		"#define COL_RGB\n"
		"#define BLURRING_DIST float(%f)\n"
		"#define IMG_DIMENSION %u\n"
		"#define SAMPLES %u\n",
		m_blurringDist, m_width, 
		static_cast<U>(initializer.get("pps.hdr.samples")));

	m_vblurFrag.load(ProgramResource::createSourceToCache(
		SHADER_FILENAME, pps.toCString(), "r_",
		getResourceManager()).toCString(),
		&getResourceManager());

	m_vblurPpline = 
		m_r->createDrawQuadProgramPipeline(m_vblurFrag->getGlProgram());

	// Set timestamps
	m_parameterUpdateTimestamp = getGlobTimestamp();
	m_commonUboUpdateTimestamp = getGlobTimestamp();
}
void execute()
{
    if(!back)//perform user commands given
    {
	if(strcmp(command[0],"quit")==0)
	    exit(0);
	else if(strcmp(command[0],"cd")==0)
	    cd();
	else if(strcmp(command[0],"fg")==0)
	{
	    int com=(int)(command[1][0]-'0');
	    fg(com);
	}
	else if(strcmp(command[0],"overkill")==0) 
	    overkill();
	else if(strcmp(command[0],"pinfo")==0)
	{
	    if(!ch)
	    {
		strcpy(list[p5].process,"pinfo");
		list[p5].back=0;
	    }
	    if(command[1][0]==0)//if only single argument given with pinfo command
		pinfo();
	    else
	    {
		int i=0,comm1,number=0,num1;
		int len1=strlen(command[1]);
		if(len1==4)
		    num1=10*10*10;
		else if(len1==3)
		    num1=10*10;
		else if(len1==2)
		    num1=10;
		else if(len1==1)
		    num1=1;
		while(i<len1)
		{
		    comm1=(int)(command[1][i]-'0');
		    number=num1*comm1+number;
		    num1=num1/10;
		    i++;
		}
		pid1(number);
	    }
	}
	else if(strcmp(command[0],"jobs")==0)
	{
	    if(!ch)
	    {
		strcpy(list[p5].process,"jobs");
		list[p5].back=0;
	    }
	    jobs();
	}
        else if(strcmp(command[0],"grep")==0)
             grep();      
	else if(strcmp(command[0],"kjob")==0)
	{
	    int comm=command[1][0]-'0';
	    int comm2=(int)(command[2][0]-'0');
            char *c1=command[1][0];
	    char *c2=command[2][0];
	    kjob((c1),(c2));
	}
	else if(strcmp(command[0],"exit")==0) 
	    fprintf(stderr,"The command is quit\n");
	else//for system defined commands
	{
	    if(!ch)
	    {
		strcpy(list[p5].process,command[0]);
		list[p5].back=0;
	    }
	    int returnval=fork();
	    if(returnval)
	    {
		list[p5++].pid=returnval;
		waitpid(returnval,&returnval,0);
	    }
	    else
	    {
		int i2=0;
		char arguments[101];
		char *args[argvals+1];
		while(i2<argvals)
		{
		    args[i2]=(char*)malloc(101*sizeof(char));
		    strcpy(args[i2],command[i2]);
		    i2++;
		}
		args[i2]=NULL;
		int flag2=1;
                if(redir_in)//incase of redirection
                {
                    if(redir_in<argvals -1)
                     {  
                      freopen(command[redir_in + 1],"r",stdin);
                      args[redir_in]=NULL;
                     }  
                    else
                     {
                     fprintf(stderr,"Give filename for redirection\n");
                     exit(0);
                     }
                }
                if(redir_out)
                {
                    if(redir_out < argvals -1)
                    {
                        freopen(command[redir_out + 1],"w",stdout);
                        args[redir_out]=NULL;
                    }
                    else
                    {
                      fprintf(stderr,"Give filename for redirection\n");
                      exit(0);
                    }
                 }                
		printf("%s",*args);
		flag2=0;
		execvp(args[0],args);//execute the command in arg
		fprintf(stderr,"Not a valid shell command\n");
		exit(0);
	    }
	}
    }
    else
    {
	if(!ch)
	{
	    strcpy(list[p5].process,command[0]);
	    list[p5].back=1;
	}
	int returnval=fork();
	if(returnval)
	{
	    if(!ch)
		list[p5++].pid=returnval;
	    printf("Command %s\t Pid %d\n",command[0],returnval);
	}
	else
	{
	    int i2=0;
	    int flag3=0;
	    char *args[argvals];
	    while(i2<back) 
	    {
		args[i2]=(char*)malloc(101*sizeof(char));
		strcpy(args[i2],command[i2]);
		i2++;
		flag3=1;
	    }
	    args[i2]=NULL;
	    execvp(args[0],args);//execute the command in args
	    fprintf(stderr,"Not a valid Shell command\n");
	    exit(0);
	}
    }
}